35

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
visil
  • 400
  • 1
  • 3
  • 6

1 Answers1

47

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523