Search code examples
javainterfaceabstract-classoverridingabstract-methods

Overriding equals method by a abstract class and set it as abstract so if any class extends, they must implement


I'm trying to build an abstract class/interface that overrides methods that already exist and set them as abstract. Is this possible?

Code example:

public abstract class Box {
    @Override
    public abstract boolean equals(Object o);
}

OR

public interface Box {
    @Override
    boolean equals(Object o);
}

Both of the class and interfaces above should have the same function, but does this mean both override Object equals method? even if I set it as abstract?

So will this work:

public class Tea extends Box {
    @Override
    public boolean equals(Object o) {
        // TODO Auto-generated method stub
        return false;
    }
}

Solution

  • First off, interfaces do not override methods. So you cannot override equals from Object by adding an equals method to an interface. Interfaces instead can be thought of as contracts, they guarantee that any non-abstract class implementing them will have all of the interfaces methods (either directly or through inheritance).

    In regards to making a method abstract through inheritance, you can in fact do this. So your example of overriding the equals method with an abstract definition in your abstract Box class will cause any classes extending Box to have to implement an equals method.

    And as @OskarEmilsson commented, if you do this then you should also force hashCode to be implemented since equals and hashCode should be consistent with each other (equals objects must have equal hashCodes).