简体   繁体   English

在main方法中实例化内部类

[英]Instantiating an inner class within a main method

When we try to instantiate an Inner class (aka: non-static Nested class) in java, say we do that in two cases: 当我们尝试在Java中实例化内部类(又名:非静态嵌套类)时,请说我们在两种情况下这样做:

1.in a main method in the same file of the outer Class in which we have two options: (ex:) 1.在外部类的相同文件中的main方法中,我们有两个选择:(ex :)

public class Test1
{
   class InnerClass
   {

   }
  public static void main(String[] args)
  {
     InnerClass inner = new Test1().new InnerClass();
  }
}

or : 要么 :

public class Test1
{
   class InnerClass
   {

   }
  public static void main(String[] args)
  {
     Test1.InnerClass inner = new Test1().new InnerClass();
  }
}
  1. In a another class (say different file), then we have the second option only and using the first option requires us (of course) to import the InnerClass.., 在另一个类(例如,不同的文件)中,那么我们只有第二个选项,使用第一个选项(当然)要求我们导入InnerClass ..,

Q: could you please explain why do we have the first option (without any import required) in the first case (the main method in the same file)? 问:您能否解释一下为什么在第一种情况(同一文件中的main方法)中有第一个选项(不需要任何导入)?

Edit: 编辑:

I guess the answer to the first question is some how related to the core idea of inner classes. 我想第一个问题的答案是与内部类的核心思想之间的关系。 but then +Q: 但是然后+ Q:

Q: Isn't an inner class a regular-member of an outer class, so if the inner class is not declared static (static nested class) then I suppose it is a non-static member and consequently its reference type, so why are we able to declare it within a static context (static method) ? 问:内部类不是外部类的常规成员,因此,如果内部类未声明为静态(静态嵌套类),则我想它是一个非静态成员,因此是其引用类型,为什么呢?我们能够在静态上下文(静态方法)中声明它?

Simply, it is because when you instantiate the inner class from a main method outside the class in which the inner class is present, the Java compiler has no way on knowing inside which class lies that inner class. 简而言之,这是因为当您从存在内部类的类之外的主要方法中实例化内部类时,Java编译器无法知道该内部类位于哪个类内部。 Hence you have to do 因此,您必须做

Test1.InnerClass innerClassObject = ...

instead of 代替

InnerClass innerClassObject = ...

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. InnerClass的实例只能存在于OuterClass的实例中,并且可以直接访问其封闭实例的方法和字段。

To instantiate an inner class, you must first instantiate the outer class. 要实例化内部类,必须首先实例化外部类。 Then, create the inner object within the outer object with this syntax: 然后,使用以下语法在外部对象内创建内部对象:

OuterClass.InnerClass innerObject = outerObject.new InnerClass(); OuterClass.InnerClass innerObject = externalObject.new InnerClass();

From Oracle Docs : https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html 从Oracle Docs: https : //docs.oracle.com/javase/tutorial/java/javaOO/nested.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM