Java Reference
In-Depth Information
An instance of a member inner class always exists within an instance of its enclosing class. The new operator is
used to create the instance of the member inner class with a slightly different syntax. The general syntax to create an
instance of a member inner class is as follows:
OuterClassReference.new MemberInnerClassConstructor()
Here, OuterClassReference is the reference of the enclosing class followed by a dot that is followed by the new
operator. The member inner class's constructor call follows the new operator. Let's revisit the first example of the
member inner class, which is
package com.jdojo.innerclasses;
public class Outer {
public class Inner {
}
}
To create an instance of the Inner member inner class, you must first create an instance of its enclosing class Outer .
Outer out = new Outer();
Now, you need to use the new operator on the out reference variable to create an object of the Inner class.
out.new Inner();
To store the reference of the instance of the Inner member inner class in a reference variable, you can write the
following statement:
Outer.Inner in = out.new Inner();
After the new operator, you always use the constructor name, which is the same as the simple class name for the
member inner class. Since the new operator is already qualified with the enclosing instance reference (as in out.new ),
the Java compiler figures out the fully qualified name of the enclosing class name automatically. It is a compile-time
error to qualify the inner class constructor with its outer class name while creating an instance of an inner class. The
following statement will result in a compile-time error:
Outer.Inner in = out.new Outer.Inner (); // A compile-time error
Consider the following class declaration with inner classes nested at multiple levels:
package com.jdojo.innerclasses;
public class OuterA {
public class InnerA {
public class InnerAA {
public class InnerAAA {
}
}
}
}
 
Search WWH ::




Custom Search