Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 default method interface override Object equals method [duplicate]

public interface Table<T> {

    @Overrride
    default boolean equals(Object other) {
        //do something and return true/false
    }
}

Why does the above code has compilation error of "java: default method equals in interface Table overrides a member of java.lang.Object"? Can't we override hashCode and equals method using interface default method, presumably I have methods in the same interface to determine the equality of the object implementing this interface?

like image 882
Wins Avatar asked Jan 19 '15 06:01

Wins


People also ask

Can java 8 default method override equals hashCode and toString?

Three of the Object methods cannot have default methods for the reasons given above by Brian Goetz: equals(Object) , hashCode() , and toString() .

Can we override default method in java interface 8?

One of the major reason for introducing default methods in interfaces is to enhance the Collections API in Java 8 to support lambda expressions. If any class in the hierarchy has a method with same signature, then default methods become irrelevant. A default method cannot override a method from java.

Can interface override object class methods?

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.

Can you override equals method?

You can override the equals method on a record, if you want a behavior other than the default. But if you do override equals , be sure to override hashCode for consistent logic, as you would for a conventional Java class.


1 Answers

No. Classes with implementations always win over default methods, so having a default hashCode or equals can never be invoked and therefore is forbidden.

like image 165
Steven Schlansker Avatar answered Oct 11 '22 04:10

Steven Schlansker