Thursday, September 9, 2010

Code to Understand Objective Static Nested Classes

Courtesy of SCJP Sun® Certified Programmer for Java™ 6 Study Guide Exam (310-065) (9780071591065)



Instantiating and Using Static Nested Classes


/*
The static modifier in this case says that the nested class is a static member of the outer class. That means it can be accessed, as with other static members, without having an instance of the outer class.

You use standard syntax to access a static nested class from its enclosing class. The syntax for instantiating a static nested class from a non-enclosing class is a little different from a normal inner class, and looks like this:
*/

class BigOuter {
  static class Nest {void go() { System.out.println("hi"); } }
}
class Broom {
  static class B2 {void goB2() { System.out.println("hi 2"); } }
  public static void main(String[] args) {
    BigOuter.Nest n = new BigOuter.Nest();   // both class names
    n.go();
    B2 b2 = new B2();     // access the enclosed class
    b2.goB2();
  }
}

No comments:

Post a Comment