Monday, February 21, 2011

Type of nested classes

A nested class is a class defined within another class. A nested classes should exist only to serve its enclosing class. If a nested class would be useful in some other context, then it should be a top-level class. This was covered in the post : Nesting of classes : Introduction.

Note : Inner classes are one type of nested class. So both cannot be inter-changeably used.

Types of nested class : Introduction
There are two types of nested classes: static and non-static.

A static nested class is one which has the static modifier applied. Because it is static, it must access the members of its enclosing class through an object. That is, it cannot refer to members of its enclosing class directly. Because of this restriction, static nested classes are seldom used.

The most important type of nested class is the inner class. An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do. Thus, an inner class is fully within the scope of its enclosing class.

Types of Nested class ( Detailed )

There are four kinds of nested classes: static member classes, nonstatic member classes, anonymous classes, and local classes.
  1. Static member classes
  2. Member classes
  3. Local classes
  4. Anonymous classes

No comments:

Post a Comment