如何在Java中调用另一个构造函数?

如何在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 而不是这个。请注意,您只能链接到一个构造函数它必须是构造函数体中的第一个语句

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.