A query about class nesting in java

mr_azad :
public class Outer{
    public class Inner{
    }
}

public class Main {
    public static void main(String[] args) {
        Outer objOut = new Outer();
        //Outer.Inner object1= objOut.new Inner();  // runes without a problem
        //objOut.Inner object2= objOut.new Inner(); //gives error
    }
}

This might sound little amateur but, What are the difference between Outer.Inner vs objOut.Inner.

T.J. Crowder :

You cannot use a variable name as the type of another variable, which is what you're trying to do with objOut.Inner. The type of the variable is Inner (or optionally Outer.Inner).

Because Inner is an inner class, it's associated with an instance of its outer class (its enclosing instance). When you create an instance of it, you can optionally¹ specify what object instance it's associated with, which is what you're doing with objOut.new Inner.

This example may help make it a bit clearer:

public class Example {
    private String str;

    public class Inner {
        void show() {
            // Show the string for the Example this Inner is part of
            System.out.println(Example.this.str);
        }
    }

    public Example(String s) {
        this.str = s;
    }

    public static void main(String[] args) {
        Example e1 = new Example("e1");
        Example e2 = new Example("e2");
        Inner i1 = e1.new Inner();
        i1.show(); // "e1"
        Inner i2 = e2.new Inner();
        i2.show(); // "e2"
    } 
}

Live Copy

Notice how the i1 Inner instance gets e1 as its enclosing Example instance, and so sees e1's str, but i2 gets e2 as its enclosing instance so it sees e2's str.

I suggest this Java tutorial for more information.


¹ Sometimes it's not optional, such as in my Example class above, since where new Inner is used, there's no default instance it could use. It would be optional in an instance method of Example, but not in that static method.

Guess you like

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