是否可以从另一个构造函数调用构造函数(在同一类中,而不是从子类中)?如果是,如何?调用另一个构造函数的最佳方法是什么(如果有几种方法可以做到这一点)?
网友回答:
用。首选模式是从最小的构造函数到最大的构造函数工作。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 的调用必须是构造函数中的第一个调用,否则将收到编译器错误。super(someValue)
网友回答:
是的,有可能:
public class Foo {
private int x;
public Foo() {
this(1);
}
public Foo(int x) {
this.x = x;
}
}
要链接到特定的超类构造函数而不是同一类中的构造函数,请使用 代替 。请注意,您只能链接到一个构造函数,并且它必须是构造函数主体中的第一个语句。super
this
另请参阅此相关问题,该问题是关于 C# 的,但原则相同。
网友回答:
[注意:我只想添加一个方面,在其他答案中我没有看到:如何克服 this() 必须在第一行的要求的限制)。]
在 Java 中,可以通过 从构造函数调用同一类的另一个构造函数。但是请注意,这必须在第一行。this()
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;
}
}
模板简介:该模板名称为【从另一个构造函数调用构造函数(在同一类中,而不是从子类中)?方法有哪些?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Java】栏目查找您需要的精美模板。