When to use static methods in Java?

Java Programming Java8Object Oriented Programming

You should use static methods whenever,

  • The code in the method is not dependent on instance creation and is not using any instance variable.
  • A particular piece of code is to be shared by all the instance methods.
  • The definition of the method should not be changed or overridden.
  • you are writing utility classes which should not be changed.

Example

Live Demo

public class InstanceCounter {
   private static int numInstances = 0;
   protected static int getCount() {
      return numInstances;
   }
   private static void addInstance() {
      numInstances++;
   }
   InstanceCounter() {
      InstanceCounter.addInstance();
   }
   public static void main(String[] arguments) {
      System.out.println("Starting with "+InstanceCounter.getCount()+" instances");
      
      for (int i = 0; i < 500; ++i) {
         new InstanceCounter();
      }
      System.out.println("Created " + InstanceCounter.getCount() + " instances");
   }
}

Output

Started with 0 instances
Created 500 instances
raja
Published on 23-Apr-2018 21:02:44
Advertisements