问题
是否有可能从另一个(在同一个类中,而不是从一个子类)调用构造函数?如果是的话如何?什么是调用另一个构造函数的最佳方法(如果有几种方法可以做到)?
#1 热门回答(2430 赞)
对的,这是可能的:
public class Foo {
private int x;
public Foo() {
this(1);
}
public Foo(int x) {
this.x = x;
}
}
要链接到一个特定的超类构造函数而不是同一个类中的构造函数,请使用super
而不是this
。请注意,您只能链接到一个构造函数和,它必须是构造函数体**中的第一条语句。
另请参阅this related question,它是关于C#的,但适用相同的原则。
#2 热门回答(193 赞)
使用this(args)
。首选模式是从最小的构造函数到最大的构造函数。
public class Cons {
public Cons() {
// A no arguments constructor that sends default values to the largest
this(madeUpArg1Value,madeUpArg2Value,madeUpArg3Value);
}
public Cons(int arg1, int arg2) {
// An example of a partial constructor that uses the passed in arguments
// and sends a hidden default value to the largest
this(arg1,arg2, madeUpArg3Value);
}
// Largest constructor that does the work
public Cons(int arg1, int arg2, int arg3) {
this.arg1 = arg1;
this.arg2 = arg2;
this.arg3 = arg3;
}
}
您也可以使用最近提倡的valueOf或“of”的方法:
public class Cons {
public static Cons newCons(int arg1,...) {
// This function is commonly called valueOf, like Integer.valueOf(..)
// More recently called "of", like EnumSet.of(..)
Cons c = new Cons(...);
c.setArg1(....);
return c;
}
}
要调用超类,使用super(asdf)
。对super的调用必须是构造函数中的第一个调用,否则您将收到编译器错误。
#3 热门回答(175 赞)
[注意:我只想添加一个方面,我在其他答案中没有看到:如何克服这个()必须在第一行的要求的限制。)
在Java中,可以通过this()
从构造函数中调用同一个类的另一个构造函数。但请注意,“这个”必须在第一行。
public class MyClass {
public MyClass(double argument1, double argument2) {
this(argument1, argument2, 0.0);
}
public MyClass(double argument1, double argument2, double argument3) {
this.argument1 = argument1;
this.argument2 = argument2;
this.argument3 = argument3;
}
}
第一行显示this
看起来是一个很大的限制,但是你可以通过静态方法构造其他构造函数的参数。例如:
public class MyClass {
public MyClass(double argument1, double argument2) {
this(argument1, argument2, getDefaultArg3(argument1, argument2));
}
public MyClass(double argument1, double argument2, double argument3) {
this.argument1 = argument1;
this.argument2 = argument2;
this.argument3 = argument3;
}
private static double getDefaultArg3(double argument1, double argument2) {
double argument3 = 0;
// Calculate argument3 here if you like.
return argument3;
}
}