本文介绍了如何在静态方法中实例化非静态内部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

public class MyClass{
   class Inner{
     int s,e,p;
   }

   public static void main(String args[]){
     Inner in;
   }
}

这部分代码很好,但我是无法在主方法中实例化'in',如 in = new Inner(),因为它显示非静态字段无法在静态上下文中引用。我能用它做什么?我不想让我的内部类静态。

Upto 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. 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();

这篇关于如何在静态方法中实例化非静态内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 20:49