class B {}
class B1 extends B {}
class B2 extends B {}
public class ExtendsTest{
public static void main(String args[]){
B b = new B();
B1 b1 = new B1();
B2 b2 = new B2();
// insert statement here
}
}
If b2 = (B2)b1 won't compile as b1 can never refer to an object of class B2 then how can b1=(B1) b compile ??but it says that it will fail at runtime..although in both cases we are assigning a reference variable of base class to a reference variable of it's derived class.
Please explain..
Did you try it out?
It is possible for a base class reference to point to a subclass object. So compiler knows that b can point to an object of class B1, therefore b1 = (B1) b; is valid at compile time.
i didn't tried but this is what i said that a base class reference can point to an object of derived class.we can apply the same to b2=(B2)b1.b1 is the base class so it can point to an object of derived class B2.