Is there any use of static methods / functions in java besides simplicity of calling?

Does the declaration of a method as static have any advantage, besides the fact that it can be called without instantiating the class?

+3
source share
3 answers

No need to create an instance of a class to call a method, it can be an end in itself. Consider libraries of methods such as java.lang.Math.

Static methods are also used as factory methods - you call a static method to get an object - usually this is an implementation of some interface. The idea is that the method can determine which specific implementation to build for you, given the parameters that you pass. If you had to have an instance of the object before you could call such a method, you would either have a chicken egg, or create instances of the second class to call the factory method to give you instances of the first.

You may also find fooobar.com/questions/88398 / ... interested, especially the accepted answer.

+4
source

There are many reasons to use methods static. Here are some examples:

  • , , , (24 AM/PM), .
  • (, Math, QuantumMechanic), - / .
  • (singleton) .

, OO, , , , , OO- , . , , .

+2

- , .

, / , , . - , : getter.

, "-" : . , - "" , , , .

, , - . , OO (Scala, , . ).

+1
source

All Articles