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.