[英]Static method with a nested class
The following code does not compile due to the line marked XX.由于标记为 XX 的行,以下代码无法编译。 If the dress() method is changed to be non-static, then this does compile.
如果将dress()方法更改为非静态方法,则可以编译。
Can someone please explain whether this is just because the dress() method doesn't have access to non-static classes or whether it's more complicated than that?有人可以解释这是否只是因为dress()方法无法访问非静态类,还是比这更复杂?
public class Wardrobe {
abstract class Sweater {
int insulate() {return 5;}
}
private static void dress() {
class Jacket extends Sweater { // XX
int insulate() {return 10;}
}
}
}
Error message:错误信息:
java: non-static variable this cannot be referenced from a static context
Your inner class Sweater
is not static inside Wardrobe
.你里面的 class
Sweater
不是 static 里面的Wardrobe
。 That means that it requires an instance of Wardrobe
.这意味着它需要一个
Wardrobe
实例。
Inside the static method dress
, there is no instance of Wardrobe
under consideration, so trying to refer the inner class Sweater
causes a compile error.在 static 方法
dress
内部,没有考虑Wardrobe
实例,因此尝试引用内部 class Sweater
会导致编译错误。
An easy fix is to make Sweater
a static nested class:一个简单的解决方法是将
Sweater
设置为 static 嵌套 class:
public class Wardrobe {
static abstract class Sweater {
int insulate() {return 5;}
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.