0

Now that I was looking into static inner class, I found that the way of object creation of static inner class and non-static inner class is different. But I don't understand why.

For non-static inner class:

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

For static inner class:

Outer.Inner inner = new Outer.Inner();
Dipendra Pokharel
  • 508
  • 1
  • 5
  • 15
  • 2
    Non-static inner classes have an implicit reference to an instance of the outer class. (Frequently, these are created by the instance itself. The double-constructor call in your first statement above can be legal, but is less frequently useful.) – Andy Thomas Jun 18 '19 at 15:41
  • In general, do not use non-static inner classes. – steven35 Jun 18 '19 at 15:44
  • 2
    @steven35 - Inner classes can be a valuable part of an outer class's implementation. For example, they can implement interfaces that the outer class does not. – Andy Thomas Jun 18 '19 at 15:48
  • 1
    Well, as you've observed yourself the difference is in the first being "non-static" and the second being "static". It's basically the same as with fields or methods: to access a non-static member (e.g. call a method) you need an instance of the class while to access a static member you'd just need the class itself. To illustrate this: make `Inner()` a method of `Outer`, let's say `public void inner()`. Now the non-static call would be `new Outer().inner()` while the static call would be `Outer.inner()`. – Thomas Jun 18 '19 at 15:49

1 Answers1

4

The entire point of a non-static class is that it's linked to an instance of the outer class.

That's why you need to create it from an instance.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964