<pre> 1:class Base{ 2: // legal code 3: } 4:class Derived1 extends Base{ 5: // legal code 6: } 7:class Derived2 extends Base{ 8: // legal code 9: } 10: public class Test 11: { 12: static public void main(String [] args) 13: { 14: Base b = new Derived1(); 15: Derived1 d1 = new Derived1(); 16: Derived2 d2 = new Derived2(); 17: b = (Base) d1; 18: b = (Base) d2; } } A. Compile time error at line 14 B. Run time error at line 18 //ANS C. Compile time error at line 17 D. NO ERRORS </pre> My thinking: line 17 and 18 should not give any Run Time error since d1 and d2 are instances of the derived classes, which are inherited from class Base. And one more question: Does lines 17 and 18 same as follows: b = d1; b = d2; And I know: d1 = (Derived1)b; //will give run time error d2 = (Derived2)b; //will give run time error Thanx in advance. [This message has been edited by Umesh (edited April 14, 2000).]
SaiRam NageshKumar
Greenhorn
Joined: Apr 06, 2000
Posts: 21
posted
0
Please check your answer once again! The code give no errors at compile and runtime. Though your thinking is correct, here what happens is: at 14 : creating ref variable of type Base which stores the new instance of Derived1. at 15 : Making an instance of Derived1. at 16 : Making an instance of Derived2. at 17 : Base class ref variable now been assigned the Base casted obj ref of Derived1 at 18 : Base class ref variable now been assigned the Base casted obj ref of Derived2. In lines 17 and 18 even you place b = d1; or (or) and b = d2; won't makes the difference. Since you can assign sub class obj to super class reference. Tha casting is 100% valid. But because of this the results of the full-pledged program may be changed. with wishes, Sai Ram
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
Sai, my ans is D gEs ans is B
maha anna
Ranch Hand
Joined: Jan 31, 2000
Posts: 1467
posted
0
Umesh, This code is perfectly ok. and NO compile error NO runtime error. And your explaination is also good. SO this post goes to our Errata Forum. regds maha anna