如何在 Java 中从另一个构造函数调用一个构造函数? [英] How do I call one constructor from another in Java?

查看:30
本文介绍了如何在 Java 中从另一个构造函数调用一个构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从另一个(在同一个类中,而不是从子类中)调用构造函数?如果是如何?调用另一个构造函数的最佳方法是什么(如果有多种方法)?

Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if there are several ways to do it)?

推荐答案

是的,这是可能的:

public class Foo {
    private int x;

    public Foo() {
        this(1);
    }

    public Foo(int x) {
        this.x = x;
    }
}

要链接到特定的超类构造函数而不是同一类中的构造函数,请使用 super 而不是 this.请注意,您只能链接到一个构造函数,并且它必须是构造函数主体中的第一条语句.

To chain to a particular superclass constructor instead of one in the same class, use super instead of this. Note that you can only chain to one constructor, and it has to be the first statement in your constructor body.

另请参阅此相关问题,该问题与 C# 有关,但适用相同的原则.

See also this related question, which is about C# but where the same principles apply.

这篇关于如何在 Java 中从另一个构造函数调用一个构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆