1

Should class methods be made static in all cases if they don't use absolutely any class fields?

Are there exceptions? According to my logic, if a class method does not use any of its fields, then it must be static. Right?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Arkady
  • 39
  • 4
  • 1
    Does this answer your question? [When to use static methods](https://stackoverflow.com/questions/2671496/when-to-use-static-methods) – Timor Sep 03 '21 at 16:35
  • Unfortunately no – Arkady Sep 03 '21 at 16:38
  • 1
    So, whats still missing after you visit the given link? – Timor Sep 03 '21 at 16:39
  • You don't need to create an object to use any of its method/field when you declare that method/field static. For better understanding see this: https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html#:~:text=Fields%20that%20have%20the%20static,one%20fixed%20location%20in%20memory. – abhimanyue Sep 03 '21 at 16:42
  • 1
    Timor, specific answer to my question – Arkady Sep 03 '21 at 16:50

1 Answers1

1

If a method doesn't use any instance variables in it's containing class then it doesn't have to be static, but it should be. As a general rule, if a method doesn't require a class instantiation to be used then it should be extracted to a utility class/interface as a static method.

Ryan
  • 1,762
  • 6
  • 11