Java Nested and Inner Class

In java programming it is possible to define a class within another class, such classes are known as nested class.

There are two types of nested classes:-                                                                                                                                1. Non-static inner class                                                                                                2.  Static inner class

Non-static inner class: Non-static inner class has a access to all of the variables and member of its outer class and can refer them directly.

 
class Outer {

    int x = 100;

    void outerShow() {
        inner innerObject = new inner();//non static inner class object obj2
        innerObject.innerShow();
    }

    class inner {

        int y = 10;	// non static inner class

        void innerShow() {
            System.out.println("outer  x =" + x);
        }
    }

    void show() {
        System.out.println("Inside show");
        //System.out.println("y =" + y);// error, y not know here
    }
}

public class TestOuter {

    public static void main(String arg[]) {
        Outer obj = new Outer();
        obj.outerShow();
        obj.show();
    }

}


 
outer  x =100
Inside show

Static inner class

static inner class can not access non-static member of its outer class. A static inner class can only access static member of its outer class.

 
class Outer {

    int x = 100;

    void call() {
        Inner innerObject = new Inner(); // static inner class object
        innerObject.show();
    }

    static class Inner // static inner class
    {

        int y = 10;

        void show() {
            
            System.out.println("  x =" + x);	 //error, x is a non static member of outer class   
            System.out.println(" y =" + y);
        }
    }
}

public class Test {

    public static void main(String arg[]) {
        Outer outerObject = new Outer();
        outerObject.call();
    }
}



Result

                This program will not compile because static inner class can not access non-static member of its outer class. But if we  will declare “x” as static then 

static int x = 100; 

the above program will run because x is a static member.

Note: In the above program, object of static inner class  created in outer class method but if we want to create object of static inner class in main() method. We can create by using syntax:

OuterClass.InnerClass  obj_name =new    OuterClass.InnerClass();