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?
Three of the Object methods cannot have default methods for the reasons given above by Brian Goetz: equals(Object) , hashCode() , and toString() .
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.
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.
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.
No. Classes with implementations always win over default methods, so having a default hashCode
or equals
can never be invoked and therefore is forbidden.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With