Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Why a Default Method Cannot Override an Object’s Methods? [Snippet]

DZone's Guide to

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.

· Java Zone ·
Free Resource

FlexNet Code Aware, a free scan tool for developers. Scan Java, NuGet, and NPM packages for open source security and open source license compliance issues.

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!

 Scan Java, NuGet, and NPM packages for open source security and license compliance issues. 

Topics:
java 8 interface ,default methods in interface ,snippet ,java ,inteface ,object ,method ,oop

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}