22 February 2011

[Technotes] Java Inner classes

First thing first, there is some terminology that needs to be explained.

In Java, you can define a class inside another class; such a class is called nested class. Nested classes can be divided into two categories: static or non-static. Static nested classes are simply called static nested classes. Non-static nested classes are called inner classes.

As for nested classes' privileges, inner classes have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class, instead, it can only access to static methods and members of the enclosing (parent) class.

To make the story even more complex, there are 2 other flavors of 'inner classes': local classes and anonymous classes (also called anonymous inner classes). You get to see lots of these two special kinds of inner classes in GUI codes. So you must understand and master them to be able to do GUI programming in Java. To see some concrete examples of these two classes, check out here and there.

In addition, you'd better read the following three web pages carefully before using inner or nested classes:

http://bit.ly/fPoJad - Nested classes introduction
http://bit.ly/dQzVvD - Inner class code example

Finally, to instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

No comments: