Why does Java 8 not allow to add a default implementation for toString() in an interface?
public interface SomeInterface { @Override default String toString(){ return ""; } }
This is the error message:
Error:(8, 20) java: default method toString in interface task1_3. SomeInterface overrides a member of java.lang.Object
Note that the interface does not define a toString() method.
By default the toString() method will return a string that lists the name of the class followed by an @ sign and then a hexadecimal representation of the memory location the instantiated object has been assigned to.
When you create a custom class or struct, you should override the ToString method in order to provide information about your type to client code. For information about how to use format strings and other types of custom formatting with the ToString method, see Formatting Types.
Interfaces can have default methods with implementation in Java 8 on later. Interfaces can have static methods as well, similar to static methods in classes. Default methods were introduced to provide backward compatibility for old interfaces so that they can have new methods without affecting existing code.
This is done to avoid problems with multiple inheritance.
The general rule is that an object cannot inherit two implementations of a single method. This rule applies in several situations - for example, when you try implementing two interfaces, both having the same method with default implementations:
interface Animal { default void saySomething() { System.out.println("Something"); } } interface Cat { default void saySomething() { System.out.println("Meow"); } } class Tiger implements Animal, Cat { // Restricted }
You must override saySomething()
in the Tiger
class above; otherwise the class will not compile.
Similarly, when you provide a default implementation of the java.lang.Object
's toString
method in an interface, you are introducing an ambiguity, because any class implementing your interface would also inherit from Object
one way or the other, so the compiler would need to decide between two implementations (despite the fact that you are trying to tell the compiler through the @override
attribute that you want your default implementation to win). In order to resolve this ambiguity, the compiler would require all classes that implement SomeInterface
to override toString
as well. However, this means that the default implementation would never be used. Hence, the language prohibits supplying it in the first place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With