Are inner classes syntactic sugar of what?

From Java in a Nutshell

Inner classes are just syntactic sugar, so locks on inner classes do not affect the inclusion class (and vice versa).

Are inner classes syntactic sugar of what? In other words, is it possible to rewrite inner classes equivalently in terms of other more basic constructions?

Thanks.

+6
source share
2 answers

Inner class Inner, for example:

package some.pkg;
class Outer {
  class Inner {}
}

becomes a compiler of this class:

package some.pkg;
class Outer$Inner {
  private final Outer this$0;

  Outer$Inner(Outer this$0) {
    this.this$0 = this$0;
  }
}

You can simply declare this class manually.

Well, it is almost like that. There are some details about giving members access Innerto instances Outer; but it is generally this.


, . .

"" , - Outer$Inner:

  some.pkg.Outer$Inner(some.pkg.Outer);
    Code:
       0: aload_0       
       1: aload_1       
       2: putfield      #1                  // Field this$0:Lsome/pkg/Outer;
       5: aload_0       
       6: invokespecial #2                  // Method java/lang/Object."<init>":()V
       9: return        

"desugared" ( $ s), :

  some.pkg.Outer$Inner(some.pkg.Outer);
    Code:
       0: aload_0       
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: aload_0       
       5: aload_1       
       6: putfield      #2                  // Field this$0:Lsome/pkg/Outer;
       9: return

, this$0 , .

, , , Outer.this (, super(Outer.this)) Outer.this ( , , , , ).

, : ; , .

+6

, - . , , , create class, ( , ). , ( ) java-, :

  • , .

  • .

  • .

+3

All Articles