This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Question: When to use static methods

I want to know when to use static methods? That means I have a class with some getter and setter methods, and I think those are only used in an instance object of a class. Does that mean I should use a static method

Such as:

Obj x = newObj(); x.someMethod(); . or: Obj.someMethod();// Is this the static way?
Copy the code

I’m very confused now

Answer a

As a 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 be defined as static.

Just like in your car class, you might have a method

double convertMpgToKpl(double mpg)
Copy the code

This method can be static, because even without ever building a car, we want to know how much 35mpg translates into.

But the following method (used to set the power of a particular car)

void setMileage(double mpg)
Copy the code

This can’t be static, because it’s impossible to call this method until the vehicle has been constructed,

By the way, this conversion doesn’t have to be correct, you might sometimes have a method that calls two car objects that are static, for example:

Car theMoreEfficientOf(Car c1, Car c2)
Copy the code

Although it can be converted to a non-static version, some people might argue that since there is no privilege to choose which car is important, you can’t force the selection of a car to call this method. But this is only a small fraction of all static methods

The article translated from Stack Overflow:stackoverflow.com/questions/2…