我有一个基类,年龄和名称作为实例成员,派生类有奖金。我在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;
}
}
答案 0 :(得分:1)
因此equals()
方法已正确实施,并且按以下方式工作:
age
和name
与Base
类bonus
类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()
。