Consider the following code:
interface Pet{ } class Bird implements Pet { } class Eagle extends Bird { } class Bat { } /* w w w . jav a 2 s . co m*/ public class Main { public static void main (String [] args) { Pet f = new Eagle (); Eagle e = new Eagle (); Bat b = new Bat (); if (f instanceof Bird) System.out.println ("f is a Bird"); if (e instanceof Pet) System.out.println ("e is a Pet"); if (b instanceof Pet) System.out.println ("f is a Bird"); } }
What will be printed when the above code is compiled and run?
Select 1 option
Correct Option is : C
Note that there is no compilation issue with b instanceof Pet because Pet is an interface and it is possible for b to point to an object of a class that is a sub class of Bat and also implements Pet.
So the compiler doesn't complain.
If you make Bat class as final, b instanceof Pet will not compile because the compiler knows that it is not possible for b to point to an object of a class that implements Pet.