Skip to content

Static

  • DO NOT belong to any instance, but belongs to the class

  • when to use ?

    • If only one instance of static member needed
    • needs to be shared across all the classes
  • Applications

    • Variables

      • value are independent of the object
      • values are supposed to be shared across the objects/instances
      • can be accessed from both class/object
    • Methods

      • to access/manipulate static variables and other static methods that don’t depend upon objects.
      • static methods are widely used in utility and helper classes.
      • cannot be overridden
      • can’t use this or super keywords
    • Blocks

      • can have multiple static blocks and are resolved in the order of existence
    • Nested class

      • Generally used for Singleton class

      • public class Singleton {
        private Singleton() {}
        private static class SingletonHolder {
        public static final Singleton instance = new Singleton();
        }
        public static Singleton getInstance() {
        return SingletonHolder.instance;
        }
        }
      • No Synchronization required

      • static nested classes can access all static members of the enclosing class, including private ones.

      • Java programming specification doesn’t allow us to declare the top-level class as static