Wednesday, April 24, 2019

Singleton pattern Vs Static Class

Q- What is the difference between singleton and static class in java
Answer: Singleton class Vs Static class

Singleton ClassStatic class
  Singleton class have only one object (an instance of the class)
  at a time per JVM. during application life cycle.
  Static class have all static member or methods.
  No need to instantiate stattic class. We can directly call methods of static class.

  public class StaticClassExample {
          private static String userName = "Sumit";
          public static String getUserName(){
          return userName;
  Singleton class represent object.  Static class represent a static methods of a class.
  Singleton class and static class provides good accessibility and save memory.
  Singleton class methods are slower then Static methods.  Static methods are much faster  because of static binding during compile time.
  Singleton class is easy to test (unit testing)  Static classes are hard test (unit testing)
  Static class provides better performance than Singleton class,
  because static methods are bonded on compile time
  Singleton classes can be lazy loaded  Static class always eagerly loaded
  When To Use :
  Singleton class is used while interested to change state of property and single object      per JVM.
  Singleton maintaining state.
  Example :-  logging, caches, thread pools, configuration settings, device driver objects
  Static class or static methods are used while don't need to change state of property. OR used to create
    utility classes.
  Static does not maintaining any state.
  Example :- java.lang.Math, Apache StringUtils

6. Can we extends singleton class in java ?
Answer: NO
Because in singleton class have private constructor.
By default when you extend a class, Java will invoke the parent's no-arg constructor when constructing the subclass.

Related Tutorials

No comments:

Post a Comment