Java Reference
In-Depth Information
The following points may be observed in the above decompiled code:
•
As usual, the compiler provided a default constructor for the
Outer
class because you did not
provide one in your source code.
•
The
Inner
class definition is entirely taken out from the body of the
Outer
class. Therefore,
the
Inner
class becomes a class that stands by itself in its compiled form. Its class name
is changed to
Outer$Inner
according to the rules discussed earlier in this chapter. By just
looking at the definition of only the
Outer$Inner
class, no one can notice that
Outer$Inner
is
the code for an inner class.
•
In the
Inner
class definition (the
Outer$Inner
class in the decompiled code), the compiler
added an instance variable named
this$0
, which is of its enclosing class type
Outer
(see the
declaration
"final Outer this$0;"
in the decompiled code
)
.
Since you did not include any constructors for the
•
Inner
class, you were expecting that the
compiler would add a default constructor. However, that is not the case. In the case of an inner
class, if you do not provide a constructor, the compiler includes a constructor, which has one
argument. The argument type is the same as its enclosing class. If you include a constructor for
an inner class, the compiler adds one argument to all the constructors you have included. The
argument is added in the beginning of the constructor's arguments list. The argument type is the
same as the enclosing class type. Consider the following declaration of the
Inner
class:
public class Outer {
public class Inner {
public Inner(int a) {
}
}
}
Now the compiler will add an extra argument to its constructor, as shown:
public class Outer$Inner {
final Outer this$0;
public Outer$Inner(Outer outer, int i) {
this$0 = outer;
super();
}
}
•
The constructor's body for the Inner class is
this$0 = outer;
super();
The first statement assigns the constructor's argument, which is the reference to its enclosed
class instance, to the instance variable. The second statement calls the default constructor of
the ancestor of the
Inner
class, which is the
Object
class in this case. Recall that if there is a
call to the ancestor's constructor inside a constructor of a class, it must be the first statement
inside the constructor. However, it is the second statement for the synthesized inner class as
shown above. Can you think of a reason why the call to the ancestor's constructor is placed as
the second statement as opposed to the first statement?