Hi Marie,
s1 = (Subclass1)s2;
It's true that the code fails to compile. The compiler complains that the assignment "s1 = (Subclass1)s2" is illegal.
I used the following code to
test it.
class Subclass1 extends Base{}
class Subclass2 extends Base
{}
class Base{
public static void main() {
Base b = new Base();
Subclass1 s1 = new Subclass1();
Subclass2 s2 = new Subclass2();
/*iilegal:*/
s1 = (Subclass1)s2;
}
}
Some rules to remember about Object Reference Casting:-
Say u want to do this, legally:-
s1 = (SubClass1)s2;
Compile-time rule:-
Assuming both s1 & s2 are classes, one class must be a subclass of the other.
Run-time rule:-
s1 must be of type Subclass1 OR MUST inherit from SubClass1.
Hope this helps
Regards,
Pragya