[英]Calling both the default and super constructor in Java
我想我想要的是根本不可能的,但我想確定一下。 說我有
public class bar {
public bar() {
}
public bar(Object stuff) {
// something done with stuff.
}
}
和擴展
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.
}
}
如何使foobar(Object stuff)盡可能簡單,同時又避免重復代碼? 我不能簡單地調用super(stuff),因為這樣就沒有完成“一些附加的foobar邏輯”,而我不能只調用this(),因為那樣我就不會做我想對“ stuff”進行的操作”。
注意:我意識到在這種情況下我實際上不需要這樣做,所以這里僅出於理論目的。
您只能鏈接到一個構造函數。 通常,最佳方法是將“較少特定”的構造函數(參數較少的構造函數)鏈接到“較特定”的構造函數,並使用單個“主”構造函數,這是唯一具有以下邏輯的構造函數:
public class FooBar extends Bar {
public FooBar() {
this(null); // Or whatever value you want for "stuff"
}
public FooBar(Object stuff) {
super(stuff);
// Initialization logic
}
}
如果添加顯式的init()
函數,該函數封裝了要在構造函數之間共享的內容,則可能會導致代碼更init()
。 特別是在您嘗試在構造函數之間跳轉的情況下。
在給出的答案中,未執行super()
構造函數。 盡管您的示例中的super()
為空,但將來不一定如此。
另外,您依靠super(foo)
正確處理foo == null
。 盡管為超類拋出IllegalArgumentException
可能是完全可以接受的,但並非針對您的用例。 基本上,您將使用帶null參數的參數化構造函數來擴展協定以正確地初始化超類。
使用init
-method方法,可以減少代碼重復,並且超類沒有擴展協定。 但是,您可能不喜歡這種樣式。 構造函數鏈接避免了其他方法。
public class foobar extends bar {
public foobar() {
super();
initFooBar(null);
}
public foobar(Object stuff) {
super(stuff);
initFooBar(stuff);
}
public void initFooBar(Object stuff) {
// some additional foobar logic here.
// "something done with stuff" here.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.