簡體   English   中英

如何訪問超類 toString 方法?

[英]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.toStringtoString定義,因此它的 class b1決定“覆蓋”祖父母的 (a1) toString方法的功能。 由於 class c1擴展了b1 -您“看到”的只是這個被覆蓋的版本,而不是a1toString版本。

現在實際上,如果您需要此功能(假設它不是 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 ,因此您可以從層次結構中的任何位置(從a1b1c1 )調用它

如果您不想允許覆蓋此受保護方法,請添加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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM