Double Nested Classes

One peculiar form of declaration that I came across while working for an aerospace company was a nested class within a nested class. The dynamics of this sort of declaration are similar to those of a normal nested class. The difference is that the dynamics extend to the subnested class as well as the nested class. See Example 6-9.

Example 6-9. A double nested class
package oracle.hcj.nested;
public class DoubleNestedClass {
 private static final String name = "Robert";
 private static String company = "Oracle";
 private int value = 5;
 public static String getCompany( ) {
 return company;
 }
 public static String getName( ) {
 return name;
 }
 public int getValue( ) {
 return value;
 }
 public static class SomeClass {
 private final static String tutorial = "Hardcore Java";
 public void someMethod( ) {
 System.out.println("In SomeClass.someMethod( )"); System.out.println(company);
 System.out.println(name);
 // System.out.println(value); // <= Compiler error
 }
 public static class SomeOtherClass {
 public void someMethod( ) {
 System.out.println("In SomeOtherClass.someMethod( )"); 
 System.out.println(company); 
 System.out.println(book); 
 }
 }
 }
}


In this example, the class SomeOtherClass is nested inside of the class SomeClass. Because of the double nesting, SomeOtherClass can access the private final static members of DoubleNestedClass as well as those of SomeClass. The dynamics extend down the nesting. Similar rules apply to method-scoped and instance-scoped double nested classes. For example, a method-scoped double nested class would have access to instance variables and final local variables of the declaring method. Regardless of how deep the nesting is, the rules propagate down. However, just because you can use double nested classes doesn't necessarily mean you should. In fact, I can't think of a single legitimate reason for double nested classes. If you find yourself writing one of these, you should probably rethink your architecture. If you find yourself doing this routinely, you may want to consider taking a long vacation.

      
Comments