为什么我得到“不能从静态上下文中引用的非静态变量"? [英] Why do I get "non-static variable this cannot be referenced from a static context"?
问题描述
我有一个非常简单的类,我想将其用作另一个类的子类.但是当我把它的代码放在父类中时,我得到:
I have a very simple class which I want to use as a subclass of another one. But when I put its code in the parent's class I get :
不能从静态上下文中引用的非静态变量
non-static variable this cannot be referenced from a static context
另一方面,当我将子类 GenTest
的类代码放在父类"类代码之外时 - JavaApp1
我没有收到此错误.>
On the other hand when I put the sublass GenTest
's class code outside the the "parent's" class code - JavaApp1
I do not get this error.
public class JavaApp1 {
class GenTest {
@Deprecated
void oldFunction() {
System.out.println("don't use that");
}
void newFunction() {
System.out.println("That's ok.");
}
}
public static void main(String[] args) {
GenTest x = new GenTest();
x.oldFunction();
x.newFunction();
}
}
为什么会这样?
推荐答案
你的嵌套类(顺便说一下,它不是子类)没有被标记为静态的,因此它是一个inner 类,需要编码类 (JavaApp1) 的实例才能构造它.
Your nested class (which isn't a subclass, by the way) isn't marked as being static, therefore it's an inner class which requires an instance of the encoding class (JavaApp1) in order to construct it.
选项:
- 将嵌套类设为静态
- 使它不是内部类(即根本不在
JavaApp1
内) 创建一个
JavaApp1
的实例作为封闭实例":
- Make the nested class static
- Make it not an inner class (i.e. not within
JavaApp1
at all) Create an instance of
JavaApp1
as the "enclosing instance":
GenTest x = new JavaApp1().new GenTest();
我个人会采用第二种方法——Java 中的嵌套类有一些奇怪的地方,所以我会使用顶级类,除非你有充分的理由让它嵌套.(最后一个选项特别混乱,IMO.)
Personally I'd go with the second approach - nested classes in Java have a few oddities around them, so I'd use top-level classes unless you have a good reason to make it nested. (The final option is particularly messy, IMO.)
请参阅第 8.1 节.有关内部类的更多信息,请参阅 JLS 的 3.
这篇关于为什么我得到“不能从静态上下文中引用的非静态变量"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!