The difference between Java-----instanceof and GetClass

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 the judgment, the following from the code to see the difference:

[Java]View PlainCopy
  1. Public class Test
  2. {
  3. public static void testinstanceof (Object x)
  4. {
  5. System.out.println ("x instanceof Parent:" + (x instanceof parent));
  6. System.out.println ("x instanceof Child:" + (x instanceof Child));
  7. System.out.println ("x getclass Parent:" + (x.getclass () = = Parent .  Class));
  8. System.out.println ("x getclass Child:" + (x.getclass () = = Child. )  Class));
  9. }
  10. public static void Main (string[] args) {
  11. Testinstanceof (new Parent ());
  12. System.out.println ("---------------------------");
  13. Testinstanceof (new Child ());
  14. }
  15. }
  16. Class Parent {
  17. }
  18. Class Child extends Parent {
  19. }
  20. /*
  21. Output:
  22. X instanceof Parent:true
  23. X instanceof Child:false
  24. X GetClass parent:true
  25. X GetClass Child:false
  26. ---------------------------
  27. X instanceof Parent:true
  28. X instanceof Child:true
  29. X GetClass Parent:false
  30. X GetClass child:true
  31. */

As you can see from the program output, the instanceof type check rule is: Do you belong to this class? Or do you belong to a derived class of that class? The operation of obtaining type information by getclass using = = To check whether it is equal is strictly judged. There is no inheritance consideration;

The difference between Java-----instanceof and GetClass

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.