BidVertiser

Wednesday, December 31, 2008

Inner classes in JAVA

The Java programming language allows you to define a class within another class. Such a class is called a nested class.

Inner classes nest within other classes. A normal class is a direct member of a package, a top-level class. Inner classes, which became available with Java 1.1, come in four flavors:

  • Static member classes
  • Member classes
  • Local classes
  • Anonymous classes

static member class is a static member of a class. Like any other static method, a static member class has access to all static methods of the parent, or top-level, class.

Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass 
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

Like a static member class, a member class is also defined as a member of a class. Unlike the static variety, the member class is instance specific and has access to any and all methods and members, even the parent's this reference.

Local classes are declared within a block of code and are visible only within that block, just as any other method variable.

 an anonymous class is a local class that has no name.

Why Use Nested Classes?

There are several compelling reasons for using nested classes, among them:
  • It is a way of logically grouping classes that are only used in one place.
  • It increases encapsulation.
  • Nested classes can lead to more readable and maintainable code.

Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.

Increased encapsulation—Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

More readable, maintainable code—Nesting small classes within top-level classes places the code closer to where it is used.


No comments: