Example of static inner class in java


Static Inner class:--
 The class which is defined inside the another class with static keyword is called  Static Inner class.


package com.javaforecast4u;
/**
 * @author Bikash
 *
 */
public class Outer {

 int a=10;
 static int b=20;
 void m1(){
  System.out.println("Outer start");
  System.out.println(a);
  System.out.println(b);
 
  Inner i=new Inner();
  System.out.println(i.x);
  System.out.println(Inner.y);
  i.show();
  Inner.test();
  System.out.println("Outer end");
 }

// Inner i=new Inner();

 static class Inner{
  int x=100;
  static y=200;  //3.
  void show(){
   System.out.println("Inner start");
   //System.out.println(a);  //1.
   System.out.println(b); 
   System.out.println(x);
   System.out.println(y);
   System.out.println("Inner end");
  }
 
  void test(){
   System.out.println("test()");
  }
 }

}




package com.javaforecast4u;
/**
 * @author Bikash
 *
 */
public class StaticInner {


 public static void main(String[] args) {
  Outer o=new Outer();
  o.m1();

  Outer.Inner oi=new Outer. Inner();
  oi.show();
  oi.test();
 }
}



Output:----
Outer start
10
20
100
200
Inner start
20
100
200
test()
Outer end

Points:---


1. Instance members of Outer class can't be access inside the static inner class directly, only static members are allowed.
2.Static  class member can't be access inside the Outer class directly.
    but allowe access with an object or class name.
     Inner i=new Inner();
System.out.println(i.x);
  System.out.println(Inner.y);
3.Static Inner class can have contain static declaration.
4.To create object of Inner class outside the Outer class ,we use  following special syntax.


  i)  Outer.Inner oi=new Outer. Inner();

Static inner class have both memebers such as instance and static but Instance Inner class have only instance members.




0 comments :

Post a Comment