Why a Default Method Cannot Override an Object’s Methods? [Snippet]
Wanting to understand why a default method cannot overrise an object's methods? Click here for the code snippet that explains why.
Join the DZone community and get the full member experience.
Join For Free
An interface cannot declare any of the methods of the object class as a default method. This restriction may be surprising, especially since the interface does not inherit from object.
Behind the scenes, an interface implicitly declares a public abstract method for most of the object’s method. As a consequence, there is no hierarchic relation between, for example, the object's equals method and the equals method that is implicitly declared in an interface. So, why does Java prohibit us from declaring an object method as the default method?
The short answer is this: Java, by design, can be misunderstood from the OOP design perspective:
interface A {
default boolean equals(Object obj) {
return true;
}
}
class B implements A {
}
Let’s suppose we have an interface, A, which declares a default method equals with the same signature as the equals method of the object class. Class B implements the A interface, which, by design, inherits the object class, and then, what version of the equals method does B inherit? A conflict would arise in this case.
Another reason is that, in this case, the interface default method becomes useless, because the equals method from the object class will always be invoked in children classes. This would conflict with the fact that the interface can be evolved. Hope this answered your question. Happy coding!
Opinions expressed by DZone contributors are their own.
Comments