Nested Class in Java

In this post, you will learn to:

  • Describe Nested Class.
  • Explain Member Class.
  • Explain Local Class.
  • Explain Anonymous Class

Nested Class

A nested class is a class defined within another class. It can have access to members of the outer or enclosing class, even if the members are declared private. Nested classes can be used for the following reasons:

Allows logical grouping of classes

If a class works as a helper class to another class, then it is logical to embed the second class within the first and keep them together.

Increases encapsulation

If class A needs access to private members of class B, then class A can be declared as nested class of class B. As a result, class A can access all the private members of Class B and at the same time class A will be hidden from the outside world.

More maintainable code

Nesting small classes within top-level classes places the code closer to where it is used. This makes it easier to maintain the code.

Advantages and Types

Nested classes have several advantages. Some of them are as follows:

  • Readable
  • Maintainable

The different types of nested classes are as follows:

  • Member classes or non-static nested classes
  • Local classes
  • Anonymous classes
  • Static Nested classes

Member Classes

A member class is a non-static inner class and is declared as a member of an outer or an enclosing class. It cannot have static modifiers because it is associated with instances. It can access all fields and methods of the outer class, but the reverse is not true. An outer class cannot access a member of an inner class, even if it is declared as public because members of an inner class are declared within the scope of inner class. A member class can be declared as public, protected, private, abstract, final, or static.

The figure below shows how to declare member classes within an outer class.

The following is the syntax to access a member class.

...
<OuterClass>.<InnerClass>
...

The following code demonstrates how to declare and access a member class.

class Member { // Top-level class
String x ;

//Declaring Inner class instance as part of member variable of 
//outer class 
Inner instanceInner;
   public static void main(String args[]) {
        // Declaring instance of Inner class
        Member.Inner theInner = new Member().new Inner(); 
        theInner.disp();
 
   }

public Member(){
    x = "Welcome to MemberClass Demo"; 
    // Instance creation of Inner class
    instanceInner = new Inner();
} 

void displayInner(){
    // Not allowed! Outclass members cannot access inner class //members
    System.out.println(y);
} 

class Inner {
   // local instance variable of Inner class
   int y=5;
   void disp() {
      System.out.println(x); 
   } 
}
}
Note: You can declare an instance variable of an inner class in the outer class as its member variable.The instance variable can be initialized in the constructor of the outer class in the same way as its other members

Local Classes

A local class is declared within a method, constructor or an initializer. In other words, a local class is declared within a block of code and is visible only within that particular block. It cannot have a static modifier. It has the ability to refer to local variables in the scope that defines them. Modifiers, such as public, protected, private, or static cannot be used in local classes.

Local classes have the following features:

  • Local classes are associated with an instance of containing class, and can access any members, including private members, of the containing class.
  • Local classes can access any local variables, method parameters, or exception parameters that are in the scope of the local method definition, provided that these are declared as final.

The figure below shows how to declare local classes within a method.

The following code demonstrates the use of a local class.

package pack;

public class Outer {
 
   /** Creates a new instance of Outer */   public Outer() {
   }
   // accessible from local class
   private int i = 100;
 
   public static void main(String args[]) {
      Outer objOuter = new Outer();
      objOuter.innmethod();
      System.out.println(objOuter.innmethod()); 
   } 
   
   int innmethod () {
      // Not accessible from local class 
      int j=5;
      // Accessible from local class 
      final int k=10;
      class InnClass { // local class
         void disp() {
            // final variable k is accessible 
            System.out.println("k="+k);
         }
      }
    return i;
   }
}

Output:

100

Anonymous Classes

An anonymous class does not have a name. It is a type of local class. It also does not allow the use of extends, implements clauses, and access modifiers, such as public, private, protected, and static. Since, it does not have a name, it cannot define a constructor. If constructor declaration is needed, then a local class can be used. An anonymous class cannot define any static fields, methods,or classes.

Anonymous interfaces are not possible to implement because an interface cannot be implemented without a name.

The figure below shows how to declare anonymous classes.

The following code demonstrates the use of anonymous class.

class Book {
    public void disp() {
    }
 
    public static void main(String args[]) {
       Title objTitle = new Title(); 
       objTitle.objBook.disp();
    }
}

class Title {
   // Anonymous class definition
   Book objBook = new Book() {
      public void disp() {
      System.out.println("Basics of Java Programming");
      }
   }; // ; indicates end of statement
}

Output:

Basics of Java Programming

Static Nested Class

A static nested class is associated with its outer class. It cannot refer directly to instance variables or methods defined in its enclosing class, but it can access class methods or variables directly. An object needs to be instantiated to access the instance variables and methods of the enclosing class.

A static nested class can be accessed using the enclosing class name.

EnclosedClass.StaticNestedClass

Static nested classes can have public, private, protected, package, final, and abstract access specifiers. Private and protected static nested classes are used to implement the internal features of a class or a class hierarchy. public static nested classes are often used to group classes together or give access to private static variables and methods to a group of classes.

The figure below shows the declaration of static nested classes.

The following code demonstrates the use of static nested class.

package pack;
class Stat {
   // accessible to static nested class
   private static final String name = "John";
   private static String company = "Dunn";
   // not accessible to static nested class
   private int age = 50;
   
   public static class Out {
      void welcome() {
         System.out.println("Welcome to Martin Limited !!");
         System.out.println(name+company);
      }
   }
}

public class StaticNestedDemo {
   static class StatInn {void desc() {
      System.out.println("Martin Limited is a Global Learning Solutions organization");
   }
}

public static void main(String args[]) {
   // Constructing instance of static nested class
   Stat.Out n = new Stat.Out();
   n.welcome();
   // Declaring constructor of public static nested class directly
   StatInn objStat = new StatInn();
   objStat.desc();
   }
}

Output:

Welcome to Martin Limited !!
JohnDunn
Martin Limited is a Global Learning Solutions organization
Related Post