The difference between java instanceof method and getclass method

***When comparing whether a class and another class belong to the same class instance, we can usually use instanceof and getClass two methods to judge whether the two are equal, but there are differences in the judgment between the two, the following Write a test class.
``java
public class Test5 {
public static void testInstanceof(Object x)
{
System.out.println("x instanceof Parent: "+(x instanceof Parent));
System.out.println("x instanceof Child: "+( x instanceof Child));
System.out.println("x getClass Parent: "+(x.getClass() == Parent.class));
System.out.println("x getClass Child: "+(x.getClass () == Child.class));
}
public static void main(String[] args) {
testInstanceof(new Parent());
System.out.println("------------- --------------");
testInstanceof(new Child());
}
}

class Parent {

}
class Child extends Parent {

}

``
***The final output is:

x instanceof Parent: true
x instanceof Child: false
x getClass Parent: true
x getClass Child: false
---------------------------------------
x instanceof Parent : true
x instanceof Child: true
x getClass Parent: false
x getClass Child: true
***From the print result, we know that the two methods are different in judgment. The logic of instanceof is: to judge whether it belongs to this class or not. If it is a subclass of this class, the return result is true; and the logic of the getclass() method is to judge whether it belongs to this class, and if it is, return true. Returns false even if the class is a derived class of the parent class. This is used to make the equals judgment of the object when the entity class overrides the equals object.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325382450&siteId=291194637