Way to call inner class by outer class

Adryr83 :

I know that to instantiate a member inner class, you have two different constructors:

First:

Outer out = new Outer();
Outer.Inner in = out.new Inner();

Second:

Outer.Inner in = new Outer().new Inner();

Now, I don't know why this code compiles:

public class Outer {

    private String greeting="Hi";

    protected class Inner {
        public int repeat=3;

        public void go() {
            for (int i =0; i<repeat; i++) {
                System.out.println(greeting);
            }
        }
    }

    public void callInner() {
        Inner in = new Inner(); //in my opinion the correct constructor is Outer.Inner in = new Inner()
        in.go();
    }

    public static void main(String[] args) {
        Outer out = new Outer();
        out.callInner();

    }
}

Why does it compile?

Thanks a lot!

Eamon Scullion :

As you are instantiating Inner within the scope of Outer (inside an instance method), you do not need to explicitly instantiate referencing the Outer clas, like in your example:

Outer.Inner in = new Outer().new Inner();

It is fine to instantiate by just referencing Inner:

 Inner in = new Inner();

This applies to all instance methods within a class, as long as they are not static.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=110936&siteId=1