Dear friends,
This is an example from Khalid' book:
class Light{/*....*/}
class LighBulb extends Light{/*....*/}
class SpotLightBulb extends LightBulb{/*...*/}
class TubeLight extends Light{/*....*/}
class NeonLight extends TubeLight{/*....*/}
public class WhoAmI{
public static void main(String[]args){
boolean result1,result2,result3;
Light light1 = new LightBulb();// (1)
// String str = (String)light1;//(2) Compile time error.
// result1 = light1 instanceof String;//(3) Compile time error.
result2 = light1 instanceof TubeLight;//(4) false Peer class.
// TubeLight tubelight1 = (TubeLight)light1 ;//(5) ClassCastException.
result3 = light1 instanceof SpotLightBulb;//(6) false superclass.
// SpotLightBulb spotref =(SpotLightBulb)light1;//(7) ClassCastException.
light1 = new NeonLight(); //(8)
if(light1 instanceof TubeLight){ //(9) true
TubeLight tubelight2 = (TubeLight)light1;// (10) OK
}
}
}
Now, (friends) please clarify line(5) and line(10).
The ref light1 at(5) denotes the object of class LightBulb.So both Tubelight
and LightBulb are peer(unrelated) classes.So,why ClasseCastException being
thrown instead of Compile time error.
At line (10) the ref light1 denotes the object of class NeonLight and is a
subclass of TubeLight.So,why the cast (TubeLight) has become necessary at
that point.
if somebody clarifies, it will be helpful.
Thanks,
kannan.