public class NestedClassTest {
public static void main(String[] args){
OuterClass.NestedClass nestedObject = new OuterClass.NestedClass();
nestedObject.printX();
OuterClass outerObject = new OuterClass();
//OuterClass.InnerClass innerObject = new outerObject.InnerClass(); //Error!
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
innerObject.printY();
//OuterClass.NestedClass objectOfNested2 = outerObject.new NestedClass(); //Error!
}
}
class OuterClass{
static int x = 10;
int y = 100;
static class NestedClass{
void printX(){
System.out.println(x);
}
}
class InnerClass{
void printY(){
System.out.println(y);
}
}
}
I was juggling with nested class and inner class. The difficult part was when I tried to initiate inner class with the keyword new
.
I expected that new outerObject.InnerClass()
would work just like
new OuterClass.NestedClass()
did. It didn't work but only outerObject.new InnerClass()
worked. To me, keyword new
coming after a variable(outerObject
in my case) seemed very eerie and confusing. Why should it be this way? What is the logic behind this?
Moreover, outerObject.new NestedClass()
didn't work, which meant more mysteries to me.
Please somebody help me understand how the keyword new
works in detail.