是否可以从另一个调用构造函数(在同一个类中,而不是从子类中)?如果是如何?调用另一个构造函数的最佳方法是什么(如果有多种方法)?
原文由 ashokgelal 发布,翻译遵循 CC BY-SA 4.0 许可协议
是否可以从另一个调用构造函数(在同一个类中,而不是从子类中)?如果是如何?调用另一个构造函数的最佳方法是什么(如果有多种方法)?
原文由 ashokgelal 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用 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(someValue)
。对 super 的调用必须是构造函数中的第一个调用,否则会出现编译错误。
原文由 Josh 发布,翻译遵循 CC BY-SA 4.0 许可协议
15 回答8.3k 阅读
8 回答6.2k 阅读
1 回答4k 阅读✓ 已解决
3 回答6k 阅读
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
2 回答3.8k 阅读
对的,这是可能的:
要链接到特定的超类构造函数而不是同一类中的构造函数,请使用
super
而不是this
。请注意, 您只能链接到一个构造函数,并且 它必须是构造函数主体中的第一条语句。另请参阅 此相关问题,该问题与 C# 有关,但适用相同的原则。