为什么我们不能以常规方式在外部类的main方法内创建内部类的实例? [英] Why we can not make an instance of inner class inside the main method of outer class in regular way?

查看:58
本文介绍了为什么我们不能以常规方式在外部类的main方法内创建内部类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何创建一个内部类的实例.但是我想知道为什么我们不能通过以下方式做到这一点:

I know how to make an instance of an inner class. But I want to know why we can not do that in the following way:

class outerclass{

      public static void main(String[] args){
              innerclass in=new innerclass();
      }

      class innerclass{


      }

}

如果执行此操作,则会出现以下错误:

If I do this then I get the following error:

No enclosing instance of type outerclass is accessible. Must qualify the allocation with an enclosing instance of type outerclass (e.g. x.new A() where x is an instance of outerclass).

为什么?

推荐答案

class Demo{

    public static void main(String[] args){
            System.out.println(innerclass.a);

    }

    static class innerclass{
            static int a=1;

    }


}

给出输出1.

将内部类设为静态时,请参见此处.您可以轻松地在外部类中进行访问,要创建Nested类的实例,您必须在其前面加上外部类名来引用它,如下所示:

See here while making the inner class as static You can easily access in your outer class,In order to create an instance of the Nested class you must reference it by prefixing it with the Outer class name, like this:

Outer.Nested instance = new Outer.Nested();

非静态嵌套类(内部类)Java中的非静态嵌套类也称为内部类.内部类与封闭类的实例相关联.因此,必须首先创建封闭类的实例才能创建内部类的实例.这是一个内部类定义示例:

Non-static Nested Classes (Inner Classes) Non-static nested classes in Java are also called inner classes. Inner classes are associated with an instance of the enclosing class. Thus, you must first create an instance of the enclosing class to create an instance of an inner class. Here is an example inner class definition:

public class Outer {

  public class Inner {
  }

}

以下是创建内部类的实例的方法:

Here is how you create an instance of the Inner class:

Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();

请注意,如何在引用外部类之后放置new以便创建内部类的实例.

Notice how you put new after the reference to the outer class in order to create an instance of the inner class.

非静态嵌套类(内部类)可以访问封闭类的字段,即使它们被声明为私有的也是如此.这是一个示例:

Non-static nested classes (inner classes) have access to the fields of the enclosing class, even if they are declared private. Here is an example of that:

public class Outer {

    private String text = "I am private!";

    public class Inner {

        public void printText() {
            System.out.println(text);
        }
    }
}

这篇关于为什么我们不能以常规方式在外部类的main方法内创建内部类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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