繁体   English   中英

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

[英]calling super.equals() in derived class while overriding equals

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

我期望输出是
此类=基础,其他类别=派生
而是输出是此类=派生,其他类别=派生

派生类的equals方法到底是做什么的,不是指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;
    }
}

因此, equals()方法已正确实现,并且可以通过以下方式工作

  1. agename的比较委托给Base
  2. 如果不相同,则返回false
  3. 否则比较Derived类中bonus字段的值

的通话super.equals()将调用equals()从超类( Base ),但this仍然是真实的实例,例如, Derived于你的情况。

派生类的equals方法到底是做什么的,不是指Base吗?

super用于调用重写的 equals方法(在Base定义的方法)。 更一般而言, super引用使用它的类型的超类,因此在这种情况下,它引用Base 但是, 在运行时引用对象的类型仍然是Derived

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

返回此对象的运行时类。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM