[英]Can I call the Super Constructor and pass the Class name in java?
我有超類Vehicle
,它是子類Plane
和Car
。 車輛從具有final string name;
的類擴展而來final string name;
字段,只能從構造函數設置。
我想將此字段設置為類的名稱,因此汽車的名稱將是汽車,飛機將是飛機,車輛將是車輛。 我想到的第一件事:
public Vehicle() {
super(getClass().getSimpleName()); //returns Car, Plane or Vehicle (Subclass' name)
}
但這給了我錯誤: Cannot refer to an instance method while explicitly invoking a constructor
。
如何仍然將name
字段設置為類名,而無需手動將其作為字符串傳入?
你不需要這樣做。
您可以直接從基本構造函數調用getClass().getSimpleName()
。
你也可以這樣做
//Vehicle constructor
public Vehicle() {
super(Vehicle.class.getSimpleName());
}
//Plane constructor
public Plane(){
super(Plane.class.getSimpleName());
}
正如編譯器告訴您的,您不能在調用“super()”方法時調用實例方法。
但是,您可以調用靜態方法。 此外,在超級構造函數代碼本身中,您始終可以調用“getClass()”,它會返回實際的實例類型。
public class A {
public A() {
System.out.println("class: " + getClass().getName());
}
}
public class B extends A {
public B() {
super();
}
}
new A(); --> "class: A"
new B(); --> "class: B"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.