The definition of some classes contains the definition of another class. This internal class is called an inner class (inner class).
For example:
public class OuterClass
{
public class InnerClass
{
//---This is a inner class.
}
}
The Innerclass class is nested in Outerclass and is declared public, and is therefore accessed by objects outside of the Outerclass class.
The Innerclass class is not declared as a static member of the Outerclass class, so no Innerclass object can be generated unless a Outerclass object is generated. However, when you declare a class object that contains nested classes, you do not necessarily generate objects of nested classes, which are primarily determined by the method of constructing the class that contains the nested class.
Example 1:
class OuterClass
{
class InnerClass
{}
}
public class Test
{
public static void main(String[] args)
{
OuterClass out = new OuterClass();
OuterClass.InnerClass in = out.new InnerClass();
}
}
We used outerclass out = new Outerclass (), and the statement generated a Outerclass class object. The Outerclass.innerclass in = Out.new innerclass () is then used, and the statement generates an object of an inner class with an instance of an external class. The two statements in the main () method can also be replaced with the following statement:
Outerclass.innerclass in = new Outerclass (). New Innerclass ();
In summary: In one Class (Test), a non-static inner class (Innerclass) in which another class (Outerclass) is created must have recourse to an instance of this outer class (Outerclass). and the declaration of this inner class object must also be in the form of Outerclass.innerclass.
Example 2:
public class Test
{
class InnerClass
{}
1
public static void main(String[] args)
{
InnerClass in = new Test().new InnerClass();
}
}
The inner class of this class can be instantiated in the main () method in the form of the previous example.
Example 3:
public class Test
{
class InnerClass
{}
InnerClass in = new InnerClass();
public static void main(String[] args)
{}
}