When comparing whether a class and another class belong to the same class instance, it is usually possible to use instanceof and getclass two methods to judge whether the two are equal, but there is a difference between the two in the judgment, the following code illustrates:
Public class Test
{
Public Static void testinstanceof (Object x)
{
System.out.println ("x instanceof Parent: instanceof parent)";
System.out.println ("x instanceof Child: 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 extends Parent {
}
/*
Output:
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
*/
As can be seen from the program output, instanceof is a type checking rule whether it belongs to the class or a derived class belonging to that class, whereas the operation of obtaining type information using = = to check for equality by GetClass is strictly judged. There are no inheritance considerations!!!
The difference between instanceof and GetClass in Java