share

Thursday, 29 January 2015

Static Class In Java

Static Class In Java

Static classes do not need the reference of the outer class. They act like an outer class within themselves. Normal non-static nested classes, on the other hand, need reference of the outer class.  In other words, static classes are independent of the outer class, while other inner classes are dependent on the outer class.

static nested class cannot access non-static (instance) data member or method.
It can access static data members of outer class including private.

 Example 1:

public class OuterClass {
 static int i=10;
static class InnerStatic{
  void print(){
  System.out.println("i="+i);
  }
}
public static void main(String[] args) {

OuterClass.InnerStatic obj=new OuterClass.InnerStatic();
obj.print();
}
}
Output:
I=10
Ex2:
public class OuterClass {
 static private int i=10;
static class InnerStatic{
  void print(){
  System.out.println("i="+i);
  }
}
public static void main(String[] args) {

OuterClass.InnerStatic obj=new OuterClass.InnerStatic();
obj.print();
}
}

Output:
i=10

Example 2:

package typeofclass;

public class OuterClass {
 int i=10;
static class InnerStatic{
  void print(){
  System.out.println("i="+i);
  }
}
public static void main(String[] args) {

OuterClass.InnerStatic obj=new OuterClass.InnerStatic();
obj.print();
}
}

Output:
Cannot make a static reference to the non-static field i

Example 3:

package typeofclass;

public class OuterClass {
     static int data=10;
     //int mark=10
static void display(){
System.out.println("data="+data);
//System.out.println("mark="+mark); error here
}

void show(){
System.out.println("In Show Method");
}

static class InnerStatic{
  void print(){
 display();
 //show(); Cannot make a static-
 //reference to the non-static method show() from the type OuterClass
  }
}
public static void main(String[] args) {

OuterClass.InnerStatic obj=new OuterClass.InnerStatic();
obj.print();
}
}

Output:
data=10


No comments:

Post a Comment