7.Java instanceof operator

Source: Internet
Author: User

Polymorphism brings up the problem of how to determine the type of object that a variable actually refers to. C + + uses Runtime-type information (RTTI), and Java uses instanceof operators.

The instanceof operator is used to determine the actual type of the object referenced by a variable, note the type of the object it refers to, not the type of the variable. Take a look at the following code:

  1. Public Final class Demo{
  2. public static void main(String[] args) {
  3. //Referencing an instance of the People class
  4. people obj = new people();
  5. if(obj instanceof Object){
  6. System. Out. println("I am an Object");
  7. }
  8. if(obj instanceof people){
  9. System. Out. println("I am Human");
  10. }
  11. if(obj instanceof Teacher){
  12. System. Out. println("I am a teacher");
  13. }
  14. if(obj instanceof President){
  15. System. Out. println("I am the headmaster");
  16. }
  17. System. Out. println("-----------"); //Dividing Line
  18. //Referencing an instance of the Teacher class
  19. obj = new Teacher();
  20. if(obj instanceof Object){
  21. System. Out. println("I am an Object");
  22. }
  23. if(obj instanceof people){
  24. System. Out. println("I am Human");
  25. }
  26. if(obj instanceof Teacher){
  27. System. Out. println("I am a teacher");
  28. }
  29. if(obj instanceof President){
  30. System. Out. println("I am the headmaster");
  31. }
  32. }
  33. }
  34. Class people{ }
  35. Class Teacher extends people{ }
  36. Class President extends Teacher{ }

Operation Result:
I am an object
I am a human being
-----------
I am an object
I am a human being
I'm a teacher.

As you can see, if the variable refers to an instance of the current class or its subclasses, instanceof returns True, otherwise false is returned.

7.Java instanceof operator

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.