Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would static methods be considered "utility methods" in an interface?

Tags:

java

static

I am reading the Java documentation about interfaces and reached the chapter about default methods. As far as I understand, when you define an interface and later add methods to it, all classes that implement this interface will break and are in need of implementing the new method.

So the documentation briefly mentions static methods as an option to mitigate this problem, but also states, that they would be viewed as "utility methods" and not essential:

If they add them as static methods, then programmers would regard them as utility methods, not as essential, core methods.

Why is this the case / why would they be viewed as "not essential"?

like image 411
hamena314 Avatar asked Oct 19 '25 08:10

hamena314


2 Answers

static methods do not work on the instance of a class, but are part of the class itself. They are most often used for utility type of tasks and therefor a little bit contradict object-orientation so should be used sparsely.

But, default methods != static methods. The docs just mention the static methods there to show how before default methods something could have been added to an interface without breaking all implementations.

Default methods are another way to add functionality to an interface without breaking existing impementations by specifying a default implementation for that method (even if it is just a throw new NotImplementedException()). And these methods can be implemented by the concrete classes that implemented this interface to provide the actual functionality they are meant for and thus overriding the default implementation of the method.

With static methods this is not possible, as they belong to the class object, not the instance and thus cannot be overridden by subclasses or implementations.

like image 185
Vampire Avatar answered Oct 22 '25 04:10

Vampire


Because you call static methods generally on class not on the Interface, eg:

Integer.parseInt(); - is called on concrete class Integer

like image 21
Rudziankoŭ Avatar answered Oct 22 '25 05:10

Rudziankoŭ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!