raja singh kumar wrote:Cat is related to Animal class and ChildBear is also related to Animal class. So both are related to each other
No, Cat and ChildBear are not related to each other. You can't relate Cat and ChildBear just because both are child classes of Animal then in that case every class we create in
Java should be related to each other as all of them directly Or indirectly subclass of Object class. Isn't It?
You can see in your mentioned scenario there is no
Cat extends ChildBear.
The instanceof operator compares an object to a specified type. You can use it to
test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
JLS 15.20.2 wrote:At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.
ChildBear -->Bear --> Animal -->Object
In main method of your example you can try such combinations to understand It more
In above code:
Line no 7-8:
It compiles successfully because there is relation between class Animal and Object i.e. Animal is subclass of Object.Both expression on line 7 and 8 returns true because at run time an object of Bear is created which can be casted to Object and Animal without raising a ClassCastException.
Same with next lines of code except
Line no 13:
bear instanceof ChildBear
It compiles successfully because there is relation between Bear and ChildBear, the reference variable bear can hold an object of Bear Or ChildBear which is determined at run time where an object of Bear is created which can't be cast to reference type i.e. ChildBear because ChildBear is subclass of Bear so this expression returns false.
Line no 22:
cat instanceof Bear
Gives compile time error because compiler is smart enough to determine reference type at compile time. It knows reference type Cat can never hold an object of Bear as there is no relation between Cat and Bear which results in compile time error.
Line no 23:
animal instanceof ChildBear
Compiles successfully because there is relation between Animal and ChildBear ( ChildBear -->Bear --> Animal ), here reference type Animal can hold an object of Animal Or Bear Or ChildBear Or Cat but at run time object of Bear is created which can't be cast to ChildBear so returns false.