Inner Classes in Java

Introduction

 It is possible to nest a class definition within another class and treat the nested class like any other method of that class. Such a class is called a Nested class. As a member of its enclosing class, a nested class has privileges to access all the members of the class enclosing it. A nested class can either be a static or nonstatic class. While static nested classes are just called static nested classes, nonstatic nested classes are called inner classes.

Inner class in Java

 An inner class is a nested class with direct access to the instance members of the class it is nested within and whose instance is contained within an instance of that class.

Syntax

class <EnclosingClass>
{
class <InnerClass>
{
<set of statements>
}
}

The interesting feature about the relationship between these two classes is not that the InnerClass is inside the EnclosingClass. Apart from these features, an instance of the InnerClass can exist only within an instance of the EnclosingClass, and it has direct access to instance variables and methods of its enclosing instance.

Open a new file in the editor and enter the following code.

public class Parcel {
    class Contents {
        private int i = 10;
        public int value() {
            return i;
        }
    }
    class Destination {
        private String label;
        Destination(String whereTo) {
            label = whereTo;
        }
        String readLabel() {
            return label;
        }
    }
    public void ship(String dest) {
        Contents c = new Contents();
        Destination d = new Destination(dest);
        System.out.println("Shipped " + c.value() + " item(s) to " + dest);
    }
    public static void main(String args[]) {
        Parcel p = new Parcel();
        p.ship("Ash");
    }
}
  • Save the file as Parcel.java
  • Compile the file using javac Parcel.java
  • Run the file using Java Parcel

Output

Java Inner Class

Coding the functionality

The above example explains the usage of the inner class. There are two inner class definitions, each with its own variables/methods, Contents, and Destinations. The enclosing class has a method ship(String dest) which creates instances of the inner classes, and this is called the main() method.

Summary 

An inner class is a nested class whose instance exists within an instance of its enclosing class and has direct access to the instance members of its enclosing instance.