Monday 16 November 2015

static classes in Java

static classes

A static class is a class declared as a static member of another class.

1. It can access static data members of outer class even including private.

2. Static nested class cannot access non-static (instance) data member or method.

class Outer { 

      private String instanceVar = "instance varibale";

      private static String staticVar = "static varibale";
      static class Inner { 
          void print() {
             System.out.println("Inside the inner class "+staticVar);

             // Cannot make a static reference to the non-static field
             // System.out.println("Inside the inner class "+instanceVar);
          }
      }
}

public class TestStaticInner {
      public static void main(String[] args) { 
            Outer.Inner obj = new Outer.Inner();
            obj.print();
      }
}

When to use nested static class in Java?

The static class is useful when the single resource is shared between all instances and generally we do this for utility classes which are required by all components and which itself doesn't have any state.

JDK usage

Map.Entry is the static inner class.

Java static nested class with static method

If you have the static member inside static nested class, you don't need to create instance of static nested class.

class Outer { 
      private String instanceVar = "instance varibale";
      private static String staticVar = "static varibale";

      static class Inner { 
          static void print() {
             System.out.println("Inside the inner class "+staticVar);
          }
      }
}

public class TestStaticInner {
      public static void main(String[] args) {
           //Method accessed without creating object static nested class
           Outer.Inner.print();
      }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...