Analysis of the difference between instanceof and getClass of in Java
- 2020-04-01 01:42:54
- OfStack
Class A {}
Class B extends A {}& cake;
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.c lass) = > True
O1. GetClass () equals (biggest lass) = > False
O2. GetClass () equals (A.c lass) = > False / / < = = = = = = = = = = = = = = = HERE
O2. GetClass () equals (biggest lass) = > True
GetClass () will be useful when you want to make sure your instance is NOT a subclass of the class you are comparing with.
A perfect equals method:
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);
}