Java Nested and Inner classes

In this lesson of Java course, we will learn about the Java nested and inner classes. We will take a look at different inner classes in Java with some examples and their uses.

1. Java Nested and Inner classes

In Java, you can always define a class inside another class. The class defined inside the other class is called inner class. Let’s take a look at this simple syntax for basic understanding of the Java nested and inner classes:

class MainClass {
    // ...
    class NestedInnerClass {
        public void doSomething() {
            System.out.println("Hello and welcome to nested class");
        }
    }
}

We can define the following type of inner or nested classes in our Java program.

  1. Static nested classes.
  2. Inner nested classes.
Java nested and inner classes

Let’s take a look at different Java nested and inner classes for better understanding:

1. Static Nested Classes

A static nested class in Java is an inner class that is declared as static using the static keyword. Keep in mind that such classes are called static nested class and not static inner class. There are few important points on the static nested class.

  • Static nested class don’t have access to the variable defined in the outer class. This is expected since the static nested class doesn’t require us to create instance of the outer class.
  • We can create instance of the static nested classes without creating object of the outer class.

Let’s look at the following example for better understanding:

public class Pizza {
    public static class PizzaType{
        int veg=3;
        int nonVeg=5;
        int vegan=1;

        public int getVegOptions(){
            return veg;
        }
        public int getTotalOptions(){
            return veg+nonVeg+vegan;
        }
    }

    public static void main(String[] args) {
         // create an object of the static nested class
         // using the name of the outer class
        Pizza.PizzaType pizzaType = new Pizza.PizzaType();

        int totalOptions = pizzaType.getTotalOptions();
        System.out.println("Total Pizza Options = "+totalOptions);

        System.out.println("Total Veg Pizza Options = "+pizzaType.getVegOptions());
    }
}

Output:

Total Pizza Options = 9
Total Veg Pizza Options = 3

Let’s understand above example in more details

  1. We created a static nested class named PizzaType inside the class Pizza.
  2. In the main method, we created an object of PizzaType using the Pizza.PizzaType pizzaType = new Pizza.PizzaType(); code.
  3. If you look closely in #2, we created object of PizzaType using the name of our outer class Pizza.

1.1. Static Nested Classes and Outer class access

There are few important things while working on Java nested and inner classes, specially the static nested classes. Let’s modify above example

public class Pizza {
    private int commonToppings;

    public Pizza() {
    }

    public Pizza(int commonToppings) {
        this.commonToppings = commonToppings;
    }

    public static class PizzaType{
        int veg=3;
        int nonVeg=5;
        int vegan=1;

        public int getVegOptions(){
            return veg;
        }
        public int getTotalOptions(){
            return veg+nonVeg+vegan;
        }
        public int getVegToppingsCount(){
            return  4+ Pizza.this.commonToppings;
        }
    }

    public static void main(String[] args) {
         // create an object of the static nested class
         // using the name of the outer class
        Pizza.PizzaType pizzaType = new Pizza.PizzaType();

        int totalOptions = pizzaType.getTotalOptions();
        System.out.println("Total Pizza Options = "+totalOptions);

        System.out.println("Total Veg Pizza Options = "+pizzaType.getVegOptions());
    }
}

In this code, we did a few modifications

  • We added a member variable commonToppings to the Pizza class.
  • In out static nested class, we are using the commonToppings value in getVegToppingsCount.

If we try to compile this code, you will see the following compile time error:

'Pizza.this' cannot be referenced from a static context
Static Nested Classes

The error is coming since we are not using the outer class object to create the instance of our inner class. Since there is no object, there is no reference to outer class.

2. Java Inner Classes

Java inner classes is a class defined inside another class. The inner class has access to the members defined in the outer class. You need to keep in mind that inner classes in the Java nested and inner classes world exists inside the outer class, we must create instance of the outer class first before instantiate the inner class. These Java inner classes are also know as non-static nested classes.

public class Car {
    private int speed;
    public class Engine {
        public void start() {
            System.out.println("The car engine is starting");
        }
        public void stop() {
            System.out.println("The car engine is stopping");
        }
    }
    public class CarType{
        public void carType(int i){
            if(i==1){
                System.out.println("Welcome to BMW...");
            }
            else{
                System.out.println("We are working hard to find your cart model");
            }
        }
    }

    public static void main(String[] args) {
        //create instance of outer class first
        Car car = new Car();

        //create instance of the inner classes using the instance of outer class
        Car.Engine engine = car.new Engine();
        Car.CarType carType = car.new CarType();

       engine.start();
       engine.stop();
       carType.carType(1);
       carType.carType(4);
    }
}

Output:

The car engine is starting
The car engine is stopping
Welcome to BMW...
We are working hard to find your cart model

3. Java Nested and Inner classes Key points

Let’s look at some of the important key point while working on Java Nested and Inner classes.

  • Inner classes are like a part of the main class. Java treats these inner classes as regular member of the class.
  • We can use the same technique to access the member of the enclosing class since java nested class are member of the outer class.
  • Nested classes help make code more readable in many cases

Summary

In this lesson ,we learned about the Java Nested and Inner classes. We saw how to define and used both inner classes and static nested classes. Inner classes are a powerful tool when used carefully. As always, the source code for this course is available on our GitHub repository.

Scroll to Top