Static class in Java



In Java concept of static class is introduced under concept of inner classes,which are specially designed for some delicate functionality in a class.

Static class in Java are allowed only for inner classes which are defined under some other class,as static outer class is not allowed which means that we can't use static keyword with outer class.

Static class are defined same as other inner class in Java only with static keyword in front of its name.These class have some unique characteristics which made them differ from other non static inner class,these features of static class are as mentioned below −

  • Static class do not need to create an instance of outer containing class in order to create its own instance.

  • Static class can access members(variables/methods) of outer containing class only if they are static in nature.Which means that a static nested class does not have access to the instance variables and methods of the outer class.

Example

Live Demo

public class StaticInnerClass {
   static String str = "hi all";
   static class Inner {
      private int a = 10;
      public void demoMethod() {
         System.out.println("Hi to all guys!");
         System.out.println("Can access properties of outer class as : "+ str);
      }
   }
   public static void main(String[] args) {
      Inner inObj = new Inner();
      inObj.demoMethod();
      System.out.println(inObj.a);
   }
}

Output

Hi to all guys!
Can access properties of outer class as : hi all
10
Rishi Raj
Rishi Raj

I am a coder


Advertisements