Class {}
Class B extends {}
Object o1 = new ();
Object o2 = new B ();
O1 instanceof A => true
O1 instanceof B => false
O2 instanceof A => true // <==================== HERE
O2 instanceof B => true
O1.getClass (). equals (A. class) => true
O1.getClass (). equals (B. class) => false
O2.getClass (). equals (A. class) => false // <=================here
O2.getClass (). equals (B. class) => true
GetClass () will be useful when you want to make sure your instance is NOT a subclass of the class you are comparing.
A perfect way to write the equals method:
Copy codeThe Code is as follows: public boolean equals (Object otherObject)
{
// A quick test to see if the objects are identical
If (this = otherObject) return true;
// Must return false if the explicit parameter is null
If (otherObject = null) return false;
// If the classes don't match, they can't be equal
If (getClass ()! = OtherObject. getClass () return false;
// Now we know otherObject is a non-null Employee
Employee other = (Employee) otherObject;
// Test whether the fields have identical values
Return name. equals (other. name) & salary = other. salary & hireDay. equals (other. hireDay );
}