When I create an instance of inner class, I use this code.
OuterClass outerClass = new OuterClass();
OuterClass.InnerClass inerClass = outerClass.new InnerClass();
But I don't understand how outerClass.new InnerClass()
works, why we use .new
it like new its inner class, I understand it is not, but I do not understand the syntax.
An inner class is POJO. So, when you look in the target directory, you see 2 (two) class files. Therefore to create an instance of the inner class you use new.
OuterClass outerClass = new OuterClass(); // create instance
OuterClass.InnerClass inerClass = outerClass.new InnerClass(); // innerClass has `this` to outerClass instance
It means that InnerClass
is not a static (i.e. has this
reference to an object of OuterClass
) and instance of OuterClass
should be created prior to it.
OuterClass.InnerClass inerClass = new OuterClass.InnerClass();
It means that InnerClass
is a static (i.e. has not this
reference to an object of Outerlass
) and it means, this is absolutely the same (from the JVM perspective) like two separate files with class OuterClass
and class InnterClass
.