本文介绍了如何在静态方法中实例化非静态内部类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下一段代码:
public class MyClass {
class Inner {
int s, e, p;
}
public static void main(String args[]) {
Inner in;
}
}
到这部分代码很好,但我无法在主要方法中实例化in",如 in = new Inner()
因为它显示了 非静态字段不能在静态上下文中引用
.
Up to this part the code is fine, but I am not able to instantiate 'in' within the main method like in = new Inner()
as it is showing non static field cannot be referenced in static context
.
我有什么方法可以做到?我不想让我的 Inner
类 static.
What is the way I can do it? I do not want to make my Inner
class static.
推荐答案
您还必须引用其他外部类.
You have to have a reference to the other outer class as well.
Inner inner = new MyClass().new Inner();
如果 Inner 是静态的,那么它将是
If Inner was static then it would be
Inner inner = new MyClass.Inner();
这篇关于如何在静态方法中实例化非静态内部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!