MySub is a subclass of Mybase: 1. MyBase objBase = new MyBase(); 2. MySub objSub = new MySub(); 3. objBase = objSub; 4. objSub = (MySub)objBase; The cast in line 4 is definately required at compile time. I had a option on the exam that asked if this was ok at runtime or possibly a runtime error. Which is it? The runtime rules for object reference casting state that the class of the expression being converted must be the "NewType" or must inherit from "NewType". Here "NewType would be the MySub class. This means that objBase must be the class MySub or a subclass of MySub. Does objBase take the class of objSub in line 4? I'm really confused now!
Since objBase can denote an object of class MySub, a cast is needed for compilation but only at runtime will we know if it will fail. It will fail if in fact objBase is denoting an object of class MyBase.
Tony Alicea Senior Java Web Application Developer, SCPJ2, SCWCD
If line #3 weren't there, would this execute (compile and run) successfully?
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
If line 3 were removed the code would compile but wouldn't run since objBase is still referencing a MyBase object and objSub expects to have a reference to a MySub object. At run time you will get a ClassCastException. Regards, Joe
Hi Frank, I had the same confusion. But I tested it. It compiles and runs fine. Pl test this code. class test1 {}; public class test2 extends test1 { public static void main(String args[]) test1 tt1 = new test1(); test2 tt2 = new test2); tt2 = tt1; tt1 = (test1)tt2; };