Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use static methods

I am wondering when to use static methods? Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method?

Example:

Obj x = new Obj(); x.someMethod(); 

...or:

Obj.someMethod(); // Is this the static way? 

I'm rather confused!

like image 710
KP65 Avatar asked Apr 19 '10 23:04

KP65


People also ask

When should static methods be used?

You should consider making a method static in Java : 1) If a method doesn't modify the state of the object, or not using any instance variables. 2) You want to call the method without creating an instance of that class.

What is the purpose of static method in Java?

The static keyword is used to create methods that will exist independently of any instances created for the class. Static methods do not use any instance variables of any object of the class they are defined in.


2 Answers

One rule-of-thumb: ask yourself "Does it make sense to call this method, even if no object has been constructed yet?" If so, it should definitely be static.

So in a class Car you might have a method:

double convertMpgToKpl(double mpg) 

...which would be static, because one might want to know what 35mpg converts to, even if nobody has ever built a Car. But this method (which sets the efficiency of one particular Car):

void setMileage(double mpg) 

...can't be static since it's inconceivable to call the method before any Car has been constructed.

(By the way, the converse isn't always true: you might sometimes have a method which involves two Car objects, and still want it to be static. E.g.:

Car theMoreEfficientOf(Car c1, Car c2) 

Although this could be converted to a non-static version, some would argue that since there isn't a "privileged" choice of which Car is more important, you shouldn't force a caller to choose one Car as the object you'll invoke the method on. This situation accounts for a fairly small fraction of all static methods, though.

like image 98
not-just-yeti Avatar answered Sep 27 '22 19:09

not-just-yeti


Define static methods in the following scenarios only:

  1. If you are writing utility classes and they are not supposed to be changed.
  2. If the method is not using any instance variable.
  3. If any operation is not dependent on instance creation.
  4. If there is some code that can easily be shared by all the instance methods, extract that code into a static method.
  5. If you are sure that the definition of the method will never be changed or overridden. As static methods can not be overridden.
like image 29
Mohd Avatar answered Sep 27 '22 21:09

Mohd