I want to know if there are any constructors involved with inner classes. for example consider the code snippet given below
class MyOuter
{
private int x= 10;
class MyInner
{
void dostuff(){
System.out.println("The value of x is "+x);
}
}
}
In another java file i create instances for both MyOuter and MyInner classes as shown below
Class Program
{
public static void main(String [] args)
{
MyOuter mo = new MyOuter();
MyOuter.MyInner mi = mo.new MyInner();
mi.dostuff();
}
}
The above code snippet compiles fine and gives output of “The value of x is 10”.
What i want to know here is whether a constructor is invoked when new() is used with MyInner class and MyOuter class. If yes, then is there any constructor chaining from inner class to outer class (like subclass calls constructor of super class and so on).
You can observe the constructor chain for the inner class when you extend an inner class.
Take this example:
and then extend the NestedClass like this
so you can see that you are able to call the super constructor of your nested class passing to that constructor the
MainClass, and calling.superonmainClassobject instance.Now you can create NestedClassExtension instances in this way:
So the main class has to exist, and its constructor it is called first. Then the constructors of the nested classes.
Instead if you want create a
NestedClassinstance outside of theMainClassyou have to write:Another time, the
MainClasshas to be created first, then the nested classes.