gpt4 book ai didi

Java equals()方法—— 'semantics of equals in subclasses'如何判断getClass和instanceof的使用

转载 作者:搜寻专家 更新时间:2023-11-01 02:20:52 40 4
gpt4 key购买 nike

我是 Java 编程的初学者。目前我正在 this 阅读关于继承和 equals 方法的内容。页。到目前为止,我理解解释:

Compare the classes of this and otherObject. If the semantics of equals can change in subclasses, use the getClass test:

if (getClass() != otherObject.getClass()) return false;

If the same semantics holds for all subclasses, you can use an instanceof test:

if (!(otherObject instanceof ClassName)) return false;

我不明白“相等语义”是什么意思。有人可以分享我们使用 getClass() 和 instanceof 的场景吗?

感谢阅读。

最佳答案

简单地说,getClass() 返回对象的直接类。例如,

class A { }

class B extends A { }

如果我们从 A 和 B 创建两个对象,

A objA = new A();
B objB = new B();

现在我们可以检查 getClass 是如何工作的

System.out.println(objA.getClass()); //Prints "class A"
System.out.println(objB.getClass()); //Prints "class B"

所以,

objA.getClass() == objB.getClass()

返回错误。但是

System.out.println(objB instanceof A); //Prints true

这是因为即使给定了所提供对象的父类(super class),instanceof 也会返回 true。

因此,当您设计 equals() 方法时,如果您想检查给定对象 (otherObject) 是从同一个直接类实例化的,请使用

 if (getClass() != otherObject.getClass()) return false;

如果给定对象 (otherObject) 甚至可以从您提供的类 (ClassName) 的子类中创建,请使用

if (!(otherObject instanceof ClassName)) return false;

简单地说,“等于的语义”意味着“您期望 equals() 方法达到的目的”。因此,您可以根据需要使用适当的方法。

关于Java equals()方法—— 'semantics of equals in subclasses'如何判断getClass和instanceof的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43906459/

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