如何在 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.