This article describes the differential analysis of instanceof and GetClass () in Java. Need a friend to reference under
Class A {}
Class B extends A {}
Object O1 = new A ();
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 () would be useful if you want to make sure your instance was not a subclass of the class you were comparing with.
A very perfect method of equals notation:
Copy CodeThe code is as follows:
public boolean equals (Object otherobject)
{
A quick test to see if the objects is 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 has identical values
Return Name.equals (other.name) && salary = = Other.salary && hireday.equals (other.hireday);
}
Analysis of differences between instanceof and GetClass () in Java