Nested & Inner Class

ht‮spt‬://www.theitroad.com

In Java, a nested class is a class that is defined within another class. There are two types of nested classes in Java: static nested classes and non-static nested classes, also known as inner classes.

A static nested class is a nested class that is declared with the "static" modifier. It is similar to a regular class, but it is defined within another class. A static nested class can access the static members of its enclosing class, but it cannot access the non-static members of the enclosing class.

Here is an example of a static nested class in Java:

public class Outer {
    private static int x = 10;

    public static class Nested {
        public void printX() {
            System.out.println(x);
        }
    }
}

In this example, the Outer class contains a static nested class called Nested. The Nested class can access the static variable x of the Outer class, but it cannot access any non-static members of the Outer class.

An inner class, on the other hand, is a non-static nested class that is defined within another class. An inner class can access both the static and non-static members of its enclosing class. Inner classes are useful for implementing certain design patterns and for creating objects that have a tight relationship with their enclosing class.

Here is an example of an inner class in Java:

public class Outer {
    private int x = 10;

    public class Inner {
        public void printX() {
            System.out.println(x);
        }
    }

    public void callInner() {
        Inner inner = new Inner();
        inner.printX();
    }
}

In this example, the Outer class contains an inner class called Inner. The Inner class can access both the static and non-static members of the Outer class. The callInner() method creates a new Inner object and calls its printX() method, which prints the value of the x variable of the Outer class.

Nested classes and inner classes are powerful features of Java that allow for more complex and modular code. They can be used to improve encapsulation and to create objects with a tight relationship to their enclosing class.