0

Is it a good practice to make all the methods in a class static if the class doesn't have any non-static class members? Like some sort of managers that don't have any instance variables of their own.

trup
  • 309
  • 1
  • 4
  • 8
  • Actually, I'd argue that it's best NOT to make all the methods of such a class static. But I think it's a matter of opinion. I wouldn't be too surprised if someone argues the opposite. – Dawood ibn Kareem May 15 '17 at 19:38
  • 1
    Note that static methods can't implement interfaces. You may want your class to implement an interface, even if it lacks instance fields. – Andy Thomas May 15 '17 at 19:40
  • 1
    @Andy good point. i.e. the java.lang.Runnable interface https://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html so instances can be executed on a thread. – Dachstein May 15 '17 at 19:56

1 Answers1

0

If the class is never going to have an instance, all the methods should be static, it would be the only way to call them (you can't do myInst.myFunc() because myInst can't exist).

This may be relevant : Static Classes In Java

The Math example is a good one, it would be confusing to have to do

Math myCalculator = new Math()
myCalculator.multiply(x,y);

unless myCalculator could have a different definition of PI, E, etc.

So in short, yes, a class that has no non-static members should have nothing but static methods

Edit : Andy Thomas made a good point

Your Math might implement the Multiplies interface, because it can multiply two things. At the same time, my MultiplierAndAdder class (I know it's a terrible class, but for the example) also implements Multiplies. In this case, the methods MUST be non-static, and you must instantiate an instance in order to pass it to whatever will be using it.

The interface logic has always been in my mind (as taught by a prof) : square peg, round hole. If you want to fit through the round hole, you have to be round. If you don't exist, you're not round, and can't go through the hole.

Community
  • 1
  • 1
Brydon Gibson
  • 1,179
  • 3
  • 11
  • 22