0

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)
 }
}
Bob
  • 105
  • 1
  • 9

2 Answers2

1

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.

Naman
  • 27,789
  • 26
  • 218
  • 353
  • So if I understood your answer correctly, the ```inner``` in the Inner class has been assigned a value, while the ```inner``` in the Outer class has not been assigned a value? – Bob Oct 22 '19 at 04:03
  • @Bob In the second case, the `inner` within the `main` method has been assigned a value while in the `Outer` class is not. – Naman Oct 22 '19 at 04:07
0

From the first code, you are trying to instantiate a non-static variable in a static method which is not allowed.

But the second snippet, you are making the instantiation locally within the method (which does not affect the value of the variable outside the method). So the second snippet works in JAVA

EricHo
  • 183
  • 10
  • 1
    No! It's got nothing to do with instantiation. It's all about _assigning_ to variables, not instantiating. – Dawood ibn Kareem Oct 22 '19 at 03:55
  • Hi Dawood ibn Kareem, could you explain more please? – EricHo Oct 22 '19 at 04:02
  • Well your answer is a bit misleading, because it talks about instantiating variables. We never instantiate variables - we instantiate classes, which means creating objects. And this particular error isn't related to instantiating the class at all. The OP is instantiating the class correctly. The problem relates to assigning the created object to a variable which isn't accessible. You seem to have mixed up "instantiating" with "assigning", and they're not the same thing at all. – Dawood ibn Kareem Oct 22 '19 at 04:14
  • Okay, maybe I have used the wrong word, I didn't pay attention to the difference before. Thanks for the explaination – EricHo Oct 22 '19 at 04:21