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:
- Public Final class Demo{
- public static void main(String[] args) {
- //Referencing an instance of the People class
- people obj = new people();
- if(obj instanceof Object){
- System. Out. println("I am an Object");
- }
- if(obj instanceof people){
- System. Out. println("I am Human");
- }
- if(obj instanceof Teacher){
- System. Out. println("I am a teacher");
- }
- if(obj instanceof President){
- System. Out. println("I am the headmaster");
- }
- System. Out. println("-----------"); //Dividing Line
- //Referencing an instance of the Teacher class
- obj = new Teacher();
- if(obj instanceof Object){
- System. Out. println("I am an Object");
- }
- if(obj instanceof people){
- System. Out. println("I am Human");
- }
- if(obj instanceof Teacher){
- System. Out. println("I am a teacher");
- }
- if(obj instanceof President){
- System. Out. println("I am the headmaster");
- }
- }
- }
- Class people{ }
- Class Teacher extends people{ }
- 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