When instantiating an inner class in Java why do I need to create a new reference to it? In the first example code a reference to Inner is made, then using that reference there is an attempt to instantiate class Inner() which doesn't work but in the second example code (where a reference to Inner is still made), the instantiation of class Inner() is successful because instead of "inner", "Inner inner" was used. So to my (noob) understanding, a new reference had to be made?
public class Outer{
Inner inner;
private class Inner{}
public static void main(String[] args){
Outer outer = new Outer;
inner = outer.new Inner(); // doesn't work (only difference in code)
}
}
public class Outer{
Inner inner;
private class Inner{}
public static void main(String[] args){
Outer outer = new Outer;
Inner inner = outer.new Inner(); // works (only difference in code)
}
}
While in the first example, the instance inner
has to be declared static
to be used in another static context.
In the latter, the global variable inner
is left unused as the local declaration and initialization takes priority.