Like Instance inner class we have also static inner class. Static instance class is loaded at the time of loading the outer class as it is declared as static that means it will act as the static member of the outer class and hence we can be able to define static member as it get initialized at the time of loading the outer class.

Important point regarding Static inner class

1. We can be able to define static and instance both in the static inner class.

2. We can have main() method which will make static inner class possible to have starting point for any java program.

3.  It can be accessed from both static and instance scope of outer class.

4. ' this ' will always refer to the outer class member , to access inner class member we need to create inner class object.

5. As it a static class then we can be able to access the static member with the class name itself. Object will be needed to access instance member.

6. Inner class is extending Object class that means we cannot use outer class member with the help of inner class object.

Example showing the working of an static inner class

public class A{

   int x;        // instance member of outer class

static class B{     // inner static class

   B(){           // inner class constructor 

        System.out.println("Inner class constructor");
}

   int x;      // inner class instance member

   static int z=40;   // inner class static member

}


A(){                    // outer class constructor

    A.B a = new A.B();   // inner class object 

    a.x=30;

   System.out.println(a.x); 

   System.out.println(this.x);

   System.out.println(A.B.z); // Accessing inner class static 
                                with class name 

}

public static void main(String[] args) {

A p = new A();

A.B b = new A.B();     // inner class in static method 

Class c = b.getClass(); //getting class name of inner class

System.out.println(c.getName());

c=c.getSuperclass();  //getting superclass name of inner class

System.out.println(c.getName());

     }
}

0 comments:

Post a Comment

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic