[英]How can I access the superclass toString method?
public class override {
public static void main(String[] args) {
c1 obj = new c1();
System.out.println(obj);
}
}
class a1 {
public String toString (){
return "this is clas a";
}
}
class b1 extends a1{
public String toString (){
return "this is clas b";
}
}
class c1 extends b1{
public String toString (){
return super.toString() + "\nthis is clas c";
}
}
我需要訪問c1
子類中的超類a1
toString
方法。 有沒有辦法做到這一點。 我正在學習 java,任何幫助都會是很大的支持。
基本上你不能 - 你不能直接訪問“祖父母”,如果它允許你這樣做,只能通過父母。
Class b1
有一個不調用super.toString
的toString
定義,因此它的 class b1
決定“覆蓋”祖父母的 (a1) toString
方法的功能。 由於 class c1
擴展了b1
-您“看到”的只是這個被覆蓋的版本,而不是a1
的toString
版本。
現在實際上,如果您需要此功能(假設它不是 toString 而是所有孩子都可能需要的一些代碼,您可以執行以下操作:
class a1 {
protected String commonReusableMethod() {
return "this is clas a";
}
public String toString (){
return commonReusableMethod();
}
}
class b1 extends a1{
public String toString (){
return "this is clas b";
}
}
class c1 extends b1{
public String toString (){
return super.toString() + "\nthis is clas c" + "\n" +
commonReusableMethod(); // you can call this method from here
}
}
注意commonReusableMethod
的定義 - 它protected
,因此您可以從層次結構中的任何位置(從a1
、 b1
、 c1
)調用它
如果您不想允許覆蓋此受保護方法,請添加final
:
protected final commonReusableMethod() {...}
您可能希望擁有super.super.toString()
類的東西。 但這在 java 中是不允許的。 所以你可以簡單地使用它兩次:
public class override {
public static void main(String[] args) {
c1 obj = new c1();
System.out.println(obj);
}
}
class a1 {
public String toString (){
return "this is clas a";
}
}
class b1 extends a1{
public String toString (){
return "this is clas b";
}
public String superToString(){
return super.toString();
}
}
class c1 extends b1{
public String toString (){
return super.superToString() + "\nthis is clas c";
}
}
這個問題也可能有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.