hamena314
hamena314

Reputation: 3109

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

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"?

Upvotes: 4

Views: 764

Answers (3)

Vampire
Vampire

Reputation: 38649

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.

Upvotes: 5

Krzysztof Krasoń
Krzysztof Krasoń

Reputation: 27476

Because static methods are self-contained, they don't depend on other methods in an interface. And more over most of the static methods in java code are actually utility methods.

Upvotes: 2

Rudziankoŭ
Rudziankoŭ

Reputation: 11251

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

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

Upvotes: 2

Related Questions