簡體   English   中英

從超類方法訪問子類靜態屬性

[英]Accessing sub class static attributes from superclass method

我將舉一個簡單的例子,因為以這種方式查看並沒有那么復雜。 以下示例的輸出將為空:

abstract class SuperClass { // it doesn't need to be abstract but that's my case now
    // needs to be static
    static String var_name = null;
    void method(){
        System.out.println(var_name);
    }
}
class subclass{
    // needs to be static
    static String var_name = "I need to print this"
    void otherUnrelatedMethod(){
        method(); // calling method() here gives me null
    }
}

我知道有兩種選擇可以實現我想要的:

只需將 var_name 作為 method() 的參數傳遞,我就可以輕松實現這一點,這是我現在正在使用的選項。

我也可以覆蓋method(),但是這樣做會帶來更多的工作,因為有很多子類並且method()實際上非常大。

除了這兩個,還有別的選擇嗎? 即:如果我可以在 method() 中指定來自“擴展 SuperClass 的東西”的變量?

對於此類問題,這是一個很好的模式:

abstract class SuperClass { 
    String var_name() {
        return null;
    }

    void method() {
        System.out.println(this.var_name());
    }
}

class subclass extends SuperClass {
    @Override
    String var_name() {
        return "I need to print this";
    }

    void otherUnrelatedMethod() {
        method(); 
    }
}

  • 首先,超類沒有關於子類的信息。 這意味着您不能從超類調用子類函數。
  • 其次, static成員存在於class ,而不存在於 instance 中。 這是不可能的,但如果一個子類覆蓋任何超類靜態成員,其他子類將成為受害者。

您最好使用從子類返回var_name@Override函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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