The difference between Java species instanceof method and GetClass method

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.