作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个非常简单的类,我想将其用作另一个类的子类。但是当我把它的代码放在父类中时,我得到:
non-static variable this cannot be referenced from a static context
另一方面,当我将子类 GenTest
的类代码放在“父”类代码之外时 - JavaApp1
我没有收到此错误。
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();
}
}
为什么会这样?
最佳答案
您的嵌套类(顺便说一句,不是子类)没有被标记为静态的,因此它是一个内部类,需要一个实例编码类 (JavaApp1) 以便构造它。
选项:
JavaApp1
中)创建 JavaApp1
的实例作为“封闭实例”:
GenTest x = new JavaApp1().new GenTest();
就我个人而言,我会选择第二种方法——Java 中的嵌套类有一些奇怪的地方,所以我会使用顶级类,除非你有充分的理由将其嵌套。 (最后一个选项特别困惑,IMO。)
参见 section 8.1.3 of the JLS有关内部类的更多信息。
关于java - 为什么我得到 "non-static variable this cannot be referenced from a static context"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10301907/
我是一名优秀的程序员,十分优秀!