You are currently viewing Java Nested and Inner Class with Example

Java Nested and Inner Class with Example

In this tutorial, you will learn about Java Nested and Inner Class with an example.

What is nested class(inner class)?

An inner class, also known as a nested class in Java, is a class that is declared within another class or interface.

  • Inner classes are used to logically group classes and interfaces in one place, making them easier to read and maintain.
  • It also has access to all of the outer class’s members, including private data members and methods.
  • You can define a class within a class in Java. The term “nested class” refers to such a type of class.
class OuterClass {
// ..
class NestedClass {
// ..
}
}

Java inner classes Advantage

In Java, there are three advantages to using inner classes. The following are the details:

  1. Nested classes represent a specific type of relationship in which the inner class can access all of the outer class’s members (data members and methods), including those that are private.
  2. Because it logically groups classes and interfaces in one place only, nested classes are used to develop more readable and maintainable code.
  3. Code Optimization: It necessitates the writing of less code.

In Java, you can create two types of nested classes.

  1. Non-static nested class (inner class)
  2. Static nested class

Non-Static Nested Class (Inner Class)

It is possible to define a class within another class in Java, these classes are referred to as nested classes. The following are the two types of nested classes: nested static class: Static nested classes are nested classes that are declared static. inner circle: A non-static nested class is an inner class.

  • A non-static nested class is one that is contained within another. It has access to the enclosing class’s members (outer class). Inner class is a term used to describe this group of people.
  • Because the inner class is contained within the outer class, you must first instantiate the outer class before proceeding to the inner class.

In Java, here’s an example of how to declare inner classes.

class CPU {
    double price;
    // nested class
    class Processor{

        // members of nested class
        double core;
        String manufact;

        double getCache(){
            return 4.0;
        }
    }

    // nested protected class
    protected class RAM{

        // members of protected nested class
        double memory;
        String manufact;

        double getClockSpeed(){
            return 5.0;
        }
    }
}

public class Main {
    public static void main(String[] args) {

        // create object of Outer class CPU
        CPU cp = new CPU();

       // create an object of inner class Processor using outer class
        CPU.Processor p = cp.new Processor();

        // create an object of inner class RAM using outer class CPU
        CPU.RAM ram = cpu.new RAM();
        System.out.println("Processor Cache is = " + p.getCache());
        System.out.println("Ram Clock speed is = " + ram.getClockSpeed());
    }
}

Output:

Processor Cache is = 4.0
Ram Clock speed is = 5.0

In the above program, there are two nested classes: Processor and RAM, both of which are contained within the outer class: CPU. The inner class can be declared protected. As a result, the RAM class has been declared protected.

Within the Main class, there are

  • We started by creating a cp instance of the outer class CPU.
  • We then created objects of inner classes using the instance of the outer class
CPU.Processor processor = cp.new Processor;

CPU.RAM ram = cp.new RAM();

Accessing Members of Outer Class within Inner Class

Using this keyword, we can get at the members of the outer class. Visit Java this keyword to learn more about this keyword.

Example: Accessing Members

class Car {
    String carName;
    String carType;

    // assign values using constructor
    public Car(String x, String y) {
        this.carName = x;
        this.carType = y;
    }

    // private method
    private String getCarName() {
        return this.carName;
    }

// inner class
    class Engine {
        String engineType;
        void setEngine() {

           // Accessing the carType property of Car
            if(Car.this.carType.equals("Turbo")){

                // Invoking method getCarName() of Car
                if(Car.this.getCarName().equals("Classic")) {
                    this.engineType = "Heavy";
                } else {
                    this.engineType = "Normal";
                }

            }else{
                this.engineType = "Normal";
            }
        }
        String getEngineType(){
            return this.engineType;
        }
    }
}

public class Main {
    public static void main(String[] args) {

// create an object of the outer class Car
        Car c = new Car("BMW"ss");

        // create an object of inner class using the outer class
        Car.Engine engine = c.new Engine();
        engine.setEngine();
        System.out.println("Engine Type for Heavy= " + engine.getEngineType());

        Car c1 = new Car("MCC", "dd");
        Car.Engine c2engine = c1.new Engine();
        c2engine.setEngine();
        System.out.println("Engine Type for Normal = " + c2engine.getEngineType());
    }
}

Output:

Engine Type for ss= Heavy
Engine Type for dd = Normal

We have the inner class Engine inside the outer class Car in the above program. Take note of the line here:

if(Car.this.carType.equals("dd")) {...}
  • this keyword is used to access the outer class’s carType variable. You may have noticed that we used Car.this.carType instead of this.carType.
  • Because if the name of the outer class Car had not been mentioned, this keyword would have represented the member of the inner class.
  • Similarly, we are calling the outer class’s method from the inner class.
  • It’s worth noting that, despite the fact that getCarName() is a private method, we can call it from the inner class.
if (Car.this.getCarName().equals("MCC") {...}

Static Nested Class

A static class, also known as a static nested class in Java, is a class that is created inside another class. It is unable to access data members and methods that are not static. It can be found by looking up the name of the outer class. It has access to the outer class’s static data members, including private.

  • We can also define a static class within another class in Java. The term “static nested class” refers to such a type of class. Static inner classes are not the same as static nested classes.
  • A static nested class, unlike an inner class, cannot access the outer class’s member variables. It’s because you don’t have to create an instance of the outer class with the static nested class.

Example: Static Nested Class

class Sample {

   // static nested class
   static class D{
       int d1 = 10;
       int d2 = 100;
       int getTotal(){
           return usb2 + usb3;
       }
   }

}
public class Main {
   public static void main(String[] args) {

       // create an object of the static nested class
       // using the name of the outer class
       Sample.D dd = new Sample.D();
       System.out.println("Value is: = " + dd.getTotal());
   }
}

Output:

Value is: 110

We’ve created a static class called D inside the Sample class in the above program. Take note of the line:

   Sample.D dd = new Sample.D();
  • We’re making a D object here by using the outer class’s name.
  • Let’s take a look at what happens if you try to access the outer class’s members

Example: Accessing members of Outer class inside Static Inner Class

class Sample {
   String model;
   public MotherBoard(String model) {
       this.model = model;
   }

   // static nested class
   static class DD{
       int u1 = 200;
       int u2 = 100;
       int getTotal(){
           // accessing the variable model of the outer classs
           if(Sample.this.model.equals("DevelopersDome")) {
               return 4;
           }
           else {
               return u1 + u2;
           }
       }
   }
}
public class Main {
   public static void main(String[] args) {

       // create an object of the static nested class
       Sample.DD u = new Sample.DD();
       System.out.println("Total Ports = " + u.getTotal());
   }
}

When we attempt to run the program, we will receive the following error:

error: non-static variable this cannot be referenced from a static context

This is due to the fact that we are not using an outer class object to create an inner class object. As a result, the outer class Motherboard is not referenced in Sample. this.

You may like:

Java Inheritance with Example | Types of inheritance

Java final Keyword with Example

Not Equal Example in Java

Java Polymorphism with Example

Hope this article will guide you to recognize all about Java Nested and Inner Class with Example that you needed and still if you have any problem or queries regarding this, post them in the comments section and we will be glad to assist you.

inner class in java, types of inner classes in java, local inner class in java,nested and inner class in java,use of inner class in java,private inner class in java, nested inner class,inner class in java, types of inner classes in java, local inner class in java,nested and inner class in java,use of inner class in java,private inner class in java, nested inner class,inner class

This Post Has 7 Comments

Leave a Reply