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.
Coming to the point, the key difference between them is that getClass() only returns true if the object is actually an instance of the specified class but an instanceof operator can return true even if the object is a subclass of a specified class or interface in Java.
equals() Method. In Java, the String equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are the same, it returns true. If all characters are not matched, then it returns false.
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).
If two Objects are equal, according to the equals(Object) method, then hashCode() method must produce the same Integer on each of the two Objects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With