When comparing whether a class belongs to the same class instance as another class, we can usually use instanceof and getclass two methods to judge whether the two are equal, but there is a difference between the two in judging, and the following is a test class.
Public classTEST5 { Public Static void testinstanceof(Object x) {System. out.println("x instanceof Parent:"+ (xinstanceofParent)); System. out.println("x instanceof Child:"+ (xinstanceofChild)); 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()); } }classParent {}classChildextendsParent {}
The result of 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 printed results to know that two methods are different in judgment, instanceof logic is: The judgment is not belong to this class, is not a subclass of this class, if the return result is true, and the logic of the GetClass () method is: The judgment is not belong to this class, if it is return true. False is returned even if the class is a derived class of the parent class. This is used when the entity class overrides the Equals object to make the equals judgment of the object.
The difference between Java species instanceof method and GetClass method