问题描述
我有一个非常简单的类,我想使用作为另一个的子类。但是当我把它的代码放在父类的类中我得到:
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 :
另一方面,当我把子类 GenTest
parent's类代码 - 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();
}
}
为什么会发生这种情况?
Why is this happening ?
推荐答案
您的嵌套类(不是一个子类)标记为静态,因此它是一个内类,它需要一个编码类(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.
:
- 设置嵌套类static
- 使其不是内部类code> 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.)
查看有关内部类的更多信息。
See section 8.1.3 of the JLS for more information about inner classes.
这篇关于为什么我得到“非静态变量这不能从静态上下文引用”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!