Java equals() method - how does 'semantics of equals in subclasses' determine the use of getClass and instanceof
equals, inheritance, java
Solution
Simply put, getClass() returns the immediate class of the object. for example,
class A { }
class B extends A { }
if we create two objects from A and B,
A objA = new A();
B objB = new B();
now we can check how getClass work
System.out.println(objA.getClass()); //Prints "class A"
System.out.println(objB.getClass()); //Prints "class B"
So,
objA.getClass() == objB.getClass()
returns false. But
System.out.println(objB instanceof A); //Prints true
This is because instanceof returns true even if a superclass is given of the provided object.
So, when you design your equals() method, if you want to check the given object(otherObject) is instantiated from the same immediate Class, use the
if (getClass() != otherObject.getClass()) return false;
If it is okay that the given object(otherObject) is made even from a subclass of a Class (ClassName) you provide, use
if (!(otherObject instanceof ClassName)) return false;
Simply, "semantics of equals" means "The purpose you expect from equals() method". So you can use the appropriate method according to your need.
Problem
I'm a beginner in Java programming. Currently I'm reading about Inheritance and the equals method at this page. I understand the explanations until this point: 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; ``` I don't understand what 'semantics of equals' mean. Can someone share scenarios where we use getClass() and instanceof please? Thank you for reading.