1
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.

TMichel
  • 4,336
  • 9
  • 44
  • 67

1 Answers1

1

An instance of an inner class belongs to a specific instance of the outer class (that's what makes it different from a static nested class). You have to say outerInstance.new InnerClass() to tell Java which outer instance that is.

A static class, on the other hand, has no associated outer instance, and so you just specify the class name with new normally (in fact, you can import the nested class directly, and then you can just say new NestedClass()).

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152