gpt4 book ai didi

java - 为什么我得到 "non-static variable this cannot be referenced from a static context"?

转载 作者:太空狗 更新时间:2023-10-29 22:53:04 28 4
gpt4 key购买 nike

我有一个非常简单的类,我想将其用作另一个类的子类。但是当我把它的代码放在父类中时,我得到:

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com