带有嵌套 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 并不是静态的 Wardrobe。这意味着它需要一个 Wardrobe.

的实例

在静态方法 dress 中,没有正在考虑的 Wardrobe 实例,因此尝试引用内部 class Sweater 会导致编译错误。

一个简单的解决方法是使 Sweater 成为静态嵌套 class:

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