Hi, It results in compiletime error as the fighter and transport classes are in no way related.It is same as follows... f16 f=new f16(); transport t=new transport(); f=t;//this will result in compile time error. Two steps to consider when instanceof operator is involved. 1.It shud pass the compiler type check. 2.Runtimeobject type shud be compatible with the type on the right hand side of the operator. Failure of step 1 will result in compile time error. Failure of step 2 will result in false. Hope this helps.. thanks, vinu. [ August 14, 2005: Message edited by: vinuharan haran ]
Hi Vinu, That information really helps.. but my question is that what do you mean by classes being related ? - should they belong to the same parent-child hierarchy/branch?
Hi, By related i mean parent/child hierarchy. Have a look at the folowing code....
obj1 instanceof two will result in compiletime error as they belong to separate branches. At the same time b instanceof one will not result in compiletime error as only the reference type of b(which is base) is checked against Right hand side type of the operator which is one.obviously base and one are related. only at run time the type of the object b holds(which is two)is tested against RHS type.Again they belong to separate branches...so false is the result. -vinu.
Sherry, you're getting an "inconvertible types" message, right? Here's the deal:
instanceof is for situations where you can't know the result until runtime. In your code, the compiler has realized that the result can't possibly be true under any circumstances, so there's not much point in creating bytecode to do the obvious. This is one of those cases where the compiler clears its throat and says, "Excuse me, but there's a better way to do this."
You'd be in a similar situation if you tries to cast falcon to Transport. Again, the compiler knows at compile time that the cast can't possibly work. Rather than making you wait until runtime (when you would get ClassCastException), the compiler posts an error as soon as the illegal cast is detected.
"falcon instanceof Transport" is like an illegal cast detected at compile time. Both result in compiler errors.
"falcon instance of SomeSubclassofF16" is like a cast that compiles but causes ClassCastException at runtime.
"falcon instaneof Fighter" is like a legal cast.
HTH, Phil
Consultant to SCJP team.<br />Co-designer of SCJD exam.<br />Co-author of "Complete Java 2 Certification Study Guide".<br />Author of "Ground-Up Java".
If you live in a cold climate and on the grid, incandescent light can use less energy than LED. Tiny ad:
a bit of art, as a gift, the permaculture playing cards