![](/img/trans.png)
[英]In Java, can you call a parent class's superclass constructor through the constructor of the child class of the parent class?
[英]Is there a way I can call a parent class constructor that takes parameters from a child class that does not have a constructor of it's own?
眾所周知,父類必須在子類之前構建; 如果父類的構造函數接受參數,則必須顯式調用父類的構造函數。 我的問題是,如果子類本身沒有構造函數,那么如何調用從子類顯式獲取參數的父類構造函數?
public class A {
public String text;
public A(String text) {
this.text = text;
}
}
public class B extends A {
// Now I must call the constructor of A explicitly (other wise I'll get a
// compilation error) but how can I do that without a constructor here?
}
答案是:你不能!
如果超類具有無參數構造函數,則編譯器也可以在子類中為您添加類似的構造函數。
但是,當超類需要參數時,編譯器不知道這些參數應來自何處。
因此:考慮向超類添加一個no args構造函數,它可以調用其他構造函數並傳遞某種默認值。 或者,您可以在派生類中執行相同的操作。
僅作記錄:沒有構造函數的Java類。 只是編譯器可能會在后台為您創建一個。 從這個角度來看,您的問題沒有多大意義。
您收到編譯錯誤,因為類A
沒有默認構造函數。 您可以在B
創建一個無參構造函數,並將一些默認文本傳遞給A
的構造函數,或者在A
創建一個無參構造函數。
public B() {
super("some default text"); //will call public A(String text)
}
如果您不願意直接調用父構造函數,則只需在子類中添加一個具有相同參數的構造函數即可,該子類僅調用父構造函數。
public class A {
public String text;
public A(String text)
{
this.text = text;
}
}
public class B extends A
{
public B(String text)
{
super(text);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.