Witscale Test Center

4.1 Nested classes


4.1 Nested classes

A nested class is any class whose declaration lies inside a body of another class or an interface. Nested classes were introduced with JDK1.1 release. They caused quite a stir initially due to their cryptic syntax. However soon they were popular with programmers due to the valuable features they provide. A nested class may be declared as a member inside the class body. The following code shows a simple top-level class EnclosingClass with two nested classes, the NestedOne and InnerOne.

 

class EnclosingClass{

    static class NestedOne {

       // static nested class’s body

    }

 

    class InnerOne {

       // Inner class body

      }

}

 

When you define a nested class which is inside a class body but not within any method or block, such nested class is called as member class. For instance, both NestedOne and InnerOne are members of class EnclosingClass. Just like other class members (i.e variables and methods), nested classes can be associated with either a class or an object of that class. In other words, you can declare a nested class as either static or non-static. The non-static nested classes are popularly known as the inner classes.

Besides the static and non-static nested class, there are two more types of inner classes depending on where they are declared within a class body. In this chapter, we will look at all the four types of nested classes, but before we dig into the details of nested classes, let us look at why we need them in the first place.