首页 > 解决方案 > 实现接口的类不能使用自己在 Equals 中插入 Object

问题描述

我试图继承一个接口,该接口包含接收另一个对象的equals方法,但在类中,我试图使用类类型,例如:class Grade,并用Grade other覆盖该方法。如果我错了,请纠正我,任何类都继承自 java 中的 Object 类。我可能不太了解接口。谢谢!

public interface Comparable {

    int Bigger(String ... args);
    
    boolean Equals(Object other);
    
}
    @Override
    public boolean Equals(Grade other) {
        if(other.getGrade() == this.getGrade() && other.getPoints() == this.getPoints() && other.getSubject() == this.getSubject())
            return true;
        return false;
    }

标签: javainterfacepolymorphism

解决方案


使用泛型:

interface Comparable<T> {
    // …
    boolean Equals(T other);
}
class Grade implements Comparable<Grade> {
    // …

    @Override
    public boolean Equals(Grade other) {
        return other.getGrade() == getGrade()
            && other.getPoints() == getPoints()
            && other.getSubject() == getSubject());
    }

推荐阅读