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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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(); } } |
1 2 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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 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();