Home > Back-end >  Are all local classes and all anonymous classes also inner classes?
Are all local classes and all anonymous classes also inner classes?

Time:09-23

This question is mostly about proper Java terminology.

I am making the distinction between an inner class, which is tied to instance of its enclosing scope, and an non-inner, nested static class which is independent of an enclosing scope instance.

public class Example {
 class Inner {
     void f1() {System.out.println(Example.this); } // Inner class can access Example's this
 }
 static class StaticClass {
     void f1() {System.out.println(this); } // Static nested class - Only its own this
 }

 public static void main(String[] args) {
 }
 void f1() {
     int local=0;
     class Local {
         void f2() {
             System.out.println(Example.this); // Local class - can access Example.this
             System.out.println(local); // can access local
         }
     }
     Runnable r = new Runnable() { 
         @Override
        public void run() {
             System.out.println(Example.this); // Anonymous local class can access Example.this
             System.out.println(local); // can access local 
        }
     };
 }
}

Is this the proper terminology and as follows, are all local classes and all anonymous classes also inner classes?

CodePudding user response:

According to the Java Language Specification:

  • An anonymous class is always an inner class (§8.1.3); it is never static (§8.1.1, §8.5.1). (15.9.5)
  • All local classes are inner classes (§8.1.3). (14.3)

CodePudding user response:

  • A nested class is any class whose declaration occurs within the body of another class or interface declaration. A nested class may be a member class, a local class , or an anonymous class.

  • Inner class is a nested class that is not explicitly or implicitly static. Inner class can refer to enclosing class instances, local variables, and type variables.

  • Local class and anonymous class can'not be static so they are inner classes.

Thus, class Inner is nested, member and inner, static class StaticClass is nested, member but not inner as it is explicitly static.

  • Related