gpt4 book ai didi

java - 在派生类中调用 super.equals() 同时重写 equals

转载 作者:行者123 更新时间:2023-11-30 03:31:00 33 4
gpt4 key购买 nike

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

我期望输出是
这个类=基类,其他类=派生
相反,输出是该类=派生,其他类=派生

派生类的 equals 方法中的 super 到底是做什么的?它不是指的是 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的比较委托(delegate)给Base
  2. 如果不相同,则返回 false
  3. 否则比较 Derived 类中 bonus 字段的值

调用 super.equals() 将会调用父类(super class) (Base) 中的 equals(),但是 this 仍然代表真实实例,例如根据您的情况派生

关于java - 在派生类中调用 super.equals() 同时重写 equals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29052335/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com