繁体   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