42

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

 5 years ago
source link: https://www.tuicool.com/articles/hit/IvyeMbE
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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.

Oct. 12, 18 · Java Zone ·

Free Resource

Join the DZone community and get the full member experience.

Verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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!

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. 


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK