如何在静态方法中实例化非静态内部类? [英] How to instantiate non static inner class within a static method?

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

问题描述

我有以下代码:

public class MyClass {

   class Inner {
     int s, e, p;
   }

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

到目前为止,代码还不错,但是我无法在像in = new Inner()这样的主要方法中实例化"in",因为它显示了non static field cannot be referenced in static context.

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静态.

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆