Java Inner Class (Nested Class) Tutorial

In this section, we will learn what the nested class is and how to use it in Java.

What is Inner Class in Java?

A class can be declared inside another class and in that case the one that is enclosed by another class is called an inner class or nested class.

Note about Inner class:

  • An inner class can access the members of the outer class no-matter what type of access specifier they have.

Java Inner Class Access Specifier

The access specifier of the inner class: It can be either `public`, `private` or `protected`.

How to create an object from an Inner class in Java:

In order to create an object from the inner class, we first need to create an object from the outer class and then use that to create a new object from the inner class. (Take a look at the example below to see how)

Example: creating object from an inner class

Create a class named `Outer` and put the code below into that class:

public class Outer {
    private String name;
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public class Inner{
        public void printName(){
            System.out.println(name);
        }
    }
}

Here in the `Outer` class, we have a private member named `name` and two methods to get and set value for this variable.

We also have a public inner class named `Inner` and it has one method in which it sends the value of the `name` variable to the output stream. (Note that the `name` variable is private but still the inner class can access the value of such variable).

Now create another class named `Simple` and put the code below into that class:

public class Simple {

    public static void main(String[] args) {
        Outer outer = new Outer();
        outer.setName("John");
        Outer.Inner inner = outer.new Inner();
        inner.printName();
    }
}

Output:

John

Here we wanted to create an object from `Inner` class and so we needed to first create an object from the `Outer` class and use it to create the `Inner` class’s object.

This is how we’ve created an object via inner class:

outer.new Inner();

Basically, first we set the name of the object that is created via outer class + dot `.` operator + the keyword `new` and finally the name of the inner class and the specific constructor that we want to use (in this example we went with the default one).

Also, look at how we used the outer class to access the inner class in order to set it as the data type of the variable that is going to store a reference of the newly created object.

Outer.Inner inner

Here we first used the name of the outer class + dot `.` operator and finally the name of the inner class.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies