How the operator instanceof exactly work? | SoloLearn: Learn to code for FREE!

+1

How the operator instanceof exactly work?

7/16/2017 8:06:45 PM

Elaf Alnayer

1 Answer

New Answer

+5

You can think of instance of as a comparison operator in which it compares object Types (including its parent Types). Object Type == Object Type class Animal {} class Dog extends Animal {} Animal a = new Animal(); Dog d = new Dog(); if(a instanceof Animal) // true System.out.println("a is an Animal"); if(d instanceof Dog) // true System.out.println("d is a Dog"); if(d instanceof Animal) // true System.out.println("d is also an Animal"); if(a instanceof Dog) // false System.out.println("a is not a Dog"); https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html