instanceof operator evaluates true or false only if the objects are linked via some inheritance and throws error otherwise
instanceof enthuware OCAJP
-
28-06-2022 - |
Question
interface Flyer{ }
class Bird implements Flyer { }
class Eagle extends Bird { }
class Bat { }
public class TestClass {
public static void main(String[] args) {
Flyer f = new Eagle();
Eagle e = new Eagle();
Bat b = new Bat();
if(f instanceof Flyer) System.out.println("f is a Flyer");
if(e instanceof Bird) System.out.println("e is a Bird");
if(b instanceof Bird) System.out.println("f is a Bird");
}
}
This is a code sample from Enthuware. I cant figure out why the third instanceof operator ( b instanceof Bird) doesn't evaluate to false but instead give me a compile time error. P.S. -i couldn't get what Enthuware was trying to explain me
The compile time error which i got was
TestClass.java:16: error: inconvertible types
if(b instanceof Bird) System.out.println("f is a Bird"); ^
required: Bird
found: Bat
1 error
La solution
Autres conseils
The third condition gives a compile time error as, Bat does not extend to Bird and as a second reason a Java class can extend a one class at most so, it is not possible for a subclass of Bat to extend to Bird class and based on this rule JVM is smart enough to figure out that Bat cannot be a Bird.