Java equals() 方法 - 'semantics of equals in subclasses' 如何确定 getClass 和 instanceof 的使用

Java equals() method - how does 'semantics of equals in subclasses' determine the use of getClass and instanceof

我是 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;

我不明白 'semantics of equals' 是什么意思。有人可以分享我们使用 getClass() 和 instanceof 的场景吗?

感谢您的阅读。

changing semantics of equals

这意味着可能equals方法可以在subclasses中被覆盖,在这种情况下使用getClass来检查对象是否属于同一个class.

In general, getClass vs instance of

当我们需要知道特定对象的 class 时,我们使用 getClass。考虑存在线性继承链的情况如下:

主类 -> 子类级别 1 -> 子类级别 2

并初始化为

MainClass mc = new SubClassLevel2();

到这里就知道层级中哪个class是我们对象的class

现在,方法实例用于您只需要检查 x 是否是 class Y 的实例的情况。它 returns 布尔值。

希望这能回答您的问题:)

简单的说,getClass()returns对象的直接class。例如,

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()

returns 错误。但是

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

这是因为 instanceof returns 即使给定对象的 superclass 也是如此。

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

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

如果给定对象 (otherObject) 甚至可以由您提供的 Class (ClassName) 的子 class 生成,请使用

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

简单来说,"semantics of equals"就是"The purpose you expect from equals() method"。所以你可以根据自己的需要使用合适的方法。