Jef*_*fed 0 java inheritance constructor super
我想我想要的是根本不可能,但我想确定.说我有
public class bar {
public bar() {
}
public bar(Object stuff) {
// something done with stuff.
}
}
Run Code Online (Sandbox Code Playgroud)
和一个扩展
public class foobar extends bar {
public foobar() {
super();
// some additional foobar logic here.
}
public foobar(Object stuff) {
// Do both the
// "some additional foobar logic" and
// "something done with stuff" here.
}
}
Run Code Online (Sandbox Code Playgroud)
如何使foobar(对象的东西)尽可能简单,同时避免重复代码?我不能简单地调用超级(东西),因为"一些额外的foobar逻辑"没有完成,我不能只调用这个()因为我不做我想做的事情"东西".
注意: 我意识到在这种情况下我实际上并不需要这样做,因此现在这只是出于理论目的.
您只能链接到一个构造函数.通常,最好的方法是将"不太具体"的构造函数(具有较少参数的构造函数)链接到"更具体"的构造函数,使用单个"主"构造函数,这是唯一具有逻辑的构造函数:
public class FooBar extends Bar {
public FooBar() {
this(null); // Or whatever value you want for "stuff"
}
public FooBar(Object stuff) {
super(stuff);
// Initialization logic
}
}
Run Code Online (Sandbox Code Playgroud)