我是Java编程的初学者.目前我在this页面上阅读有关继承和等于方法的内容.
直到这一点,我理解这些解释:
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()
返回false.但
System.out.println(objB instanceof A); //Prints true
这是因为即使给出了提供的对象的超类,instanceof也会返回true.
因此,当您设计equals()方法时,如果要检查给定对象(otherObject)是否从同一个直接类实例化,请使用
if (getClass() != otherObject.getClass()) return false;
如果可以从您提供的Class(ClassName)的子类创建给定对象(otherObject),请使用
if (!(otherObject instanceof ClassName)) return false;
简单地说,“equals的语义”意味着“你期望从equals()方法的目的”.因此,您可以根据需要使用适当的方法.
标签:java,inheritance,equals
来源: https://codeday.me/bug/20190608/1197046.html