簡體   English   中英

Static 嵌套方法 class

[英]Static method with a nested class

由於標記為 XX 的行,以下代碼無法編譯。 如果將dress()方法更改為非靜態方法,則可以編譯。

有人可以解釋這是否只是因為dress()方法無法訪問非靜態類,還是比這更復雜?

public class Wardrobe {
    abstract class Sweater {
        int insulate() {return 5;}
    }
    private static void dress() {
        class Jacket extends Sweater {    // XX
            int insulate() {return 10;}
        }
    }
}

錯誤信息:

java: non-static variable this cannot be referenced from a static context

你里面的 class Sweater不是 static 里面的Wardrobe 這意味着它需要一個Wardrobe實例。

在 static 方法dress內部,沒有考慮Wardrobe實例,因此嘗試引用內部 class Sweater會導致編譯錯誤。

一個簡單的解決方法是將Sweater設置為 static 嵌套 class:

public class Wardrobe {
    static abstract class Sweater {
        int insulate() {return 5;}
    }
    ...
}

暫無
暫無

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

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