在覆盖equals时调用派生类中的super.equals()

时间:2015-03-14 18:04:11

标签: java inheritance equals override

我有一个基类,年龄和名称作为实例成员,派生类有奖金。我在Derived类中重写了equals。我知道当有一个基类时,equals如何在Java中工作。但是我无法理解它在继承的情况下是如何工作的。我想检查两个派生对象是否相等。

我期待输出为
此class = Base,Other class = Derived
相反,输出是 此class = Derived,Other class = Derived

什么是超级等于派生类的方法呢?它不​​是指Base?

<br/>

public class Base{

    private int age;
    private String name;

    public Base(int age, String name){
        this.age = age;
        this.name = name;
    }

    public int getAge(){
        return age;
    }

    public String getName(){
        return name;
    }

    @Override
    public boolean equals(Object otherBase){

        //Check if both the references refer to same object
        if(this == otherBase){
            return true;
        }

        if(otherBase == null){
            return false;
        }

        System.out.println("This class       ="+this.getClass().getCanonicalName()+", Other class = "+otherBase.getClass().getCanonicalName());

        if(this.getClass() != otherBase.getClass()){
            return false;
        }

        if(! (otherBase instanceof Base)){
            return false;
        }

        Base other = (Base) otherBase;

        return this.age == other.age && this.name.equals(other.name);
       }


    public static void main(String[] args){
        Derived d1 = new Derived(10,6,"shri");
        Derived d2 = new Derived(10,5, "shri");
        if(d1.equals(d2)){
            System.out.println("Equal");
        }else{
            System.out.println("Not Equal");
        }
    }
}

class Derived extends Base{

    private int bonus;

    public int getBonus(){
        return bonus;
    }

    public Derived(int bonus, int age, String name){
        super(age, name);
        this.bonus = bonus;
    }

    @Override
    public boolean equals(Object otherDerived){
        if(!(super.equals(otherDerived))){
            return false;
        }

        Derived derived = (Derived) otherDerived;
        return bonus == derived.bonus;
    }
}

2 个答案:

答案 0 :(得分:1)

因此equals()方法已正确实施,并且按以下方式工作

  1. 委派agenameBase
  2. 的比较
  3. 如果不相同,则返回false
  4. 否则比较bonus
  5. Derived字段的值

    super.equals()的来电将从超类(equals())调用Base,但this仍代表真实实例,例如在您的情况下Derived

答案 1 :(得分:1)

  

什么是超级等于派生类的方法呢?它不​​是指Base?

super用于调用 overriden equals方法(Base中定义的方法)。更一般地说,super引用了使用它的类型的超类,所以在这种情况下是的,它引用Base。但是,引用对象的类型 在运行时 仍为Derived

Base#equals()方法中,表达式this.getClass().getCanonicalName()在运行时返回对象的类名。即使在基类的equals方法中调用表达式,实际类型也是Derived。这就是Javadocs中提到的getClass方法的作用:

  

返回此Object的 runtime 类。

如果您需要获取超类的名称,可以使用this.getClass().getSuperclass().getCanonicalName()