Originally posted by Veena Point:
class Color {}
class Red extends Color {}
class Blue extends Color {}
class A {
public static void main (String[] args) {
Color c1 = new Red();
Color c2 = new Blue();
Red r1 = new Red();
boolean b1 = c1 instanceof Color; //line 1
boolean b2 = c1 instanceof Blue; //line2
//boolean b3 = r1 instanceof Blue;
System.out.print(b1+","+b2);
}
}
Above programme prints true false.Shouldn't line 2 give compiler error?I am confused.Actually left hand side operand of instanceof operator should be reference type or object type?For ex in the line c1 instanceof Color c1 reffers to "Color" or "Red"...Hope I make some sense.
Please anybody explain.
Veena
Hi Veena,
The
instanceof operator behaves differently between compile time and runtime.
To pass compilation, the reference (1st operand) must be assignable to the 2nd operand.
Assignable means that you can cast the reference implicitly or explicitly to the type of the 2nd operand.
In short, if you can do this between the 2 operands, then you will pass compilation:
In line 2 in the code above, c1, which is of type Color, can be assigned to type Blue(by explicit cast).
This is why the compilation did not fail.
Now during runtime, in order to return TRUE, the
object pointed to by the reference must be assignable to the 2nd operand
w/o an explicit cast. In short, you must be able to do this between the 2 operands for it to return TRUE:
Obviously, line 2 returned FALSE because you cannot do this:
Hope this helps
