本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看活动链接
提问:如何在Java中从另一个调用一个构造函数?
是否可以从另一个(在同一类中,而不是在子类中)调用构造函数?如果是,怎么办?调用另一个构造函数的最佳方法是什么(如果有几种方法可以做到)?
高分回答:
是的,有可能:
public class Foo {
private int x;
public Foo() {
this(1);
}
public Foo(int x) {
this.x = x;
}
}
要链接到特定的超类构造函数而不是同一类中的构造函数,请使用super代替this。请注意,您只能链接到一个构造函数,它必须是构造函数主体中的第一条语句。
高分回答:
使用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;
}
}
文章翻译自 am2dgbqfb6mk75jcyanzabc67y-ac4c6men2g7xr2a-stackoverflow-com.translate.goog/questions/2…
作者建议:源码都是这样儿的
真心感谢帅逼靓女们能看到这里,如果这个文章写得还不错,觉得有点东西的话
求点赞👍 求关注❤️ 求分享👥 对8块腹肌的我来说真的 非常有用!!!
如果本篇博客有任何错误,请批评指教,不胜感激 !❤️❤️❤️❤️