Monday, 29 July 2013

No-Arguments Default Constructor and Nested Classes (Non-Static Inner Class, Local Class, Anonymous Class)

Last week, I was working with different type of nested classes and found an interesting fact (which I overlooked up-till now) regarding no-arguments default constructor in some of the nested classes.

Before, I illustrate the example, as a refresher, lets briefly look how many types of Nested Classes are supported in Java.

Types of Nested Classes supported in Java:

  1. Static Nested Class – a static class nested inside another class
  2. Non-Static Nested Class – also called Inner Class – a non static class nested inside another class. Besides that, there are two other, special kinds of Inner Classes:
    1. Local Class – a named Inner Class
    2. Anonymous Class – an un-named Inner Class

Consider following class, in which I tried to create all different sorts of test cases regarding nested classes. Although I don’t wanted to add any extra code to illustrate these cases, but in order to gain “access” to certain members, I had to open doors here and there, please ignore them.

And then I create following Test Runner sort-of a class which basically access different nested test classes created inside the top level class above and to display their information for our analysis.

When you run the Test class, following output will be displayed on your console:

Note following interesting observations:

  1. All nested classes, regardless of their type mentioned above, are mechanically generated by the compiler and hence a “$” in their fully qualified names. [Java Language Specification 3.8]
  2. Among all nested classes, static nested class is the only one that “retains” its constructor’s original signatures in the original form. All the other nested classes “looses” their constructor’s original signatures.
  3. For all the nested classes, other than the static nested class, following is true:
    1. If your nested class has no constructors defined, then don’t expect the default no-argument constructor to be available in these classes.
    2. If you nested class has one or more constructors defined, then don’t expect them to “retain” their original constructor signatures after compilation or at runtime.
    3. Why? because, java compiler, when compiles these nested classes, it “adds” an additional parameter at the very first (0 – zero) index of ALL constructors of a nested class. This additional parameter is actually the enclosing object’s reference. [Java Language Specification 8.1.3]

Now, if you refer to your Java Bean definition:

JavaBeans are are classes that are (1) serializable, (2) have a 0-argument constructor, and (3) allow access to properties using getter and setter methods.

So, by definition, all your non-static inner classes, local classes and anonymous classes disqualifies as JavaBeans.