Nested and Inner Class in Java.

With Java you can write a Class that is enclosed within another Class. These are called Nested Class. ONe Usually goes for Nested Class when the New Class which you are creating is very closely Associated with a Class which is already available in your codebase and will be used only by that particular Class. Depending upon the usage there are different types of Nested Classes.

  1. Non-Static Nested Class. (Also called as Inner Class)
  2. Static Nested Class.
  3. Local Class (Nested Class inside a code block)
  4. Anonymous Nested Class.

Before we go into details of each of the types of Nested Class. Let’s first understand the data access of Nested Class inside an Enclosing Class. A Nested Class have access to all the data members of Enclosing Class even the private members. However the Enclosing Class does not have access to the data Member’s of Nested Class directly.

Non-Static Nested Class

A Non-Static Nested Class or a Inner Class id defined without the static keyword and has access to all the member’s of the Outer Class, and can refer to them Directly without creating the Object of Outer Class. Let’s consider this example.

class Outer {
    int outer_x = 100;

    void test() {
        Inner inner = new Inner();
        inner.display();
    }

    // this is an Inner Class
    class Inner {
        void display() {
            System.out.println("display: outer_x = " + outer_x);
        }
    }

}

class InnerClassDemo {
    public static void main(String args[]){
        Outer outer = new Outer();
        outer.test();
    }
}

Output:

display: outer_x = 100

Static Nested Class

A static Nested Class only have access to the static data members of the enclosing Class. It cannot access non-static members of Outer Class.

Local Class

Local classes in Java are like inner classes that are defined inside a method or scope block ({ … }) inside a method. Here is an example:

class Outer {

    public void testMethod(){
        class LocalClass{
            
            int x = 10;
            
            public void display(){
                System.out.println("This is a local class")
            }
        }
    }
}

Local classes can only be accessed from inside the method or scope block in which they are defined.

Local classes can access members (fields and methods) of its enclosing class just like regular inner classes.

Related Articles

If you like our content, please consider buying me a coffee.

Thank you for your support!

Buy me a coffeeBuy me a coffee

Leave a reply:

Your email address will not be published.

Site Footer