JavaA Simple Guide to Using Nested Classes in Java

A Simple Guide to Using Nested Classes in Java

Java Programming tutorials

A nested class is a class defined inside another class. It is a member of the outer class and can therefore use any of the four visibility modifiers, just like the class fields and methods.

In this Java programming tutorial, developers will learn how to use nested classes and other Object-oriented programming (OOP) concepts.

What Are Nested Classes in Java?

Nested classes have access to all the members of the outer class, including those declared as private. Note, however, that the reverse is not true; outer classes can not access members of the inner class.

Nesting classes allows the programmer to logically group classes that will only be used by certain classes. Additionally, nesting allows for easy maintainability of code – a core principle of OOP programming.

In the sections below, you will learn how to use the four types of nested classes in Java.

Read: Understanding Java Objects and Java Classes

What is a Static Nested Class in Java?

A nested class can either be static or non-static. A static class is one that is defined with the keyword static. Such a class can only access the instance members of the outer class by object referencing. However, it can access the static members of the enclosing class directly.

The syntax for writing a static nested class in Java can be seen in the following code example:

class OuterClass {

    static class NestedStaticClass{

}
}

You create an instance of a static nested class in the usual way you instantiate other top-level classes:

NestedStaticClass nestedObj = new NestedStaticClass();

The sample code below shows how you can access static members and instance members of an outer class from a static nested class in Java:

public class OuterClassStaticExample{
   int x=15;
   static double y = 178.5;
 
   static class StaticNestedClass{
       void show(OuterClassStaticExample outer){
           System.out.println("\nThe instance field, x, from OuterClass is "+ outer.x);                      
           System.out.println("\nThe static field, y, from OuterClass is "+ y);
       }
   }
 
   public static void main(String args[]){
       StaticNestedClass inner = new StaticNestedClass();
       OuterClassStaticExample outerStatic = new OuterClassStaticExample();
       inner.show(outerStatic);
   }
}

Read: String Objects in Java

How Do You Use an Inner Class in Java?

A non-static nested (also called an inner class) class is one that is defined without the keyword static. It can directly access the members of an outer class. An inner class can not declare any static members since it is associated with an instance and not a class. Here is the syntax of an inner class in Java:

class OuterClass {

    class InnerClass{

}
}

It is also possible to instantiate an inner class. However, you can only create and use objects of an inner class within an outer class.

To create an object of an inner, you need to first instantiate the outer class then the inner class next, as in the following code example:

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

Take note of the syntax for creating an instance of the inner class. Consider the example below, where the display() method of an inner class is called in an outer class using Java:

public class OuterClass{
   int x=15;
 
   class InnerClass{
       void display(){
           System.out.println("\nThe variable x from OuterClass is "+ x);
       }
   }
 
   public static void main(String args[]){
       OuterClass outer = new OuterClass();
       OuterClass.InnerClass inner = outer.new InnerClass();
       inner.display();
   }
}

Read: The Top Java IDEs

What is a Local Inner Class in Java?

You can also create a nested class inside a block (for loop, while loop, if.. else, etc). Such a class is called a local class. They are usually declared in methods:

// code fragment 
void distance (int x, int y){

  class LocalInnerClass{

}
}

A local nested class is an inner class since it can not access static members on an outer class. This class can only access final members of an outer class.

What is Anonymous Inner Class in Java?

An anonymous inner class is an inner class that does not have a name. It provides the benefit of making your code brief since both declaration and instantiation are done at the same time. A good place to use it would be if you intended to use a local class once. Here is the syntax:

ClassType AnonymousClass = new ClassType(args){

};

Or you can use:

InterfaceType AnonymousClass = new InterfaceType(){

};

The declaration of an anonymous nested class consists of the following parts:

  • The class name or interface name that the anonymous class extends or implements
  • The new operator
  • Parentheses to pass the constructor arguments, similar to instances in the usual classes.
  • The body of the class. Note that only method declarations are allowed and not statements.

Summary of Nested Classes in Java

Nested classes provide developers with a way to logically group classes and also enable you to increase encapsulation in your programming.

It is also interesting to know that after compiling a class (Outer) that has a nested class (Nested), a class file called Outer$Nested.class is also created. Therefore, be sure to transfer it as well when you are deploying your outer class.

Read: A Guide to Constructor Chaining in Java

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories