Search code examples
javainner-classesanonymous-inner-classlocal-class

Can we say that a method-local class is a type of Inner class?


Since we can not use the static modifier with a local class defined inside a method, and since Nonstatic nested classes are Inner classes, we could probably say that a method local class is a type of an Inner class.

But on the other hand, we say that instances of Inner classes CAN NOT exist without a Live instance of the enclosing class. But an instance of a method-local class defined in a static method CAN exist without a live instance of the enclosing class, right?

So what do I conclude from this? The first logic tells me that local classes are a type of Inner class, and the second piece of reasoning tells me that Local class is not an Inner class.


Solution

  • we say that instances of Inner classes CAN NOT exist without a Live instance of the enclosing class

    No. From the JLS (emphasis mine):

    An inner class C is a direct inner class of a class or interface O if O is the immediately enclosing type declaration of C and the declaration of C does not occur in a static context.

    [...]

    An instance i of a direct inner class C of a class or interface O is associated with an instance of O, known as the immediately enclosing instance of i.

    This tells us that one may have an inner class that does not have an enclosing instance. In particular, this occurs in situations where it's defined in a static context.