I got this question in a Mock Exam. class ApBase extends Object implements Runnable. 1. Apbase aBase = new ApBase(); 2. Runnable aR = aBase; 3. Object obj = aR; 4. Apbase x = (Apbase)obj; What will happen when we try to compile and run? a. Compiler objects to line 2. b. Compiler objects to line 3. c.Code compiles but when run , throws ClassCastException in line 4. d. Compiles and runs fine. My answer is c. Author answer is d. If you go by Simon Roberts Complete Java2 Certification book, page no 118. Newtype nt; Oldtype ot; nt = (New type)ot. Run time casting rule is If New type is a class, the class of the expression being converted must be Newtype or must inherit fron Newtype. okay. In our case 4. Apbase x = (Apbase)obj; class of expression is object which is neither the same class of x or subclass of x.
Supree, Newtype nt; Oldtype ot; nt = (New type)ot. Apbase x = (Apbase)obj; This is the case of nt->non-final class lt ->non-final class The compile time rules for object ref casting is Oldtype must extend Newtype or vice versa Here Apbase is subclass of class Object. So it is right. I think you are referring to the other table The rules for object reference assignment conversion regds maha anna
Joined: Feb 25, 2000
Hi Mahanama, Compile time is okay. but will die in run time. right. Pl refer run time casting rules in Simon Robert's book. thanks
Joined: Jan 31, 2000
class ApBase extends Object implements Runnable. 1. Apbase aBase = new ApBase(); 2. Runnable aR = aBase; 3. Object obj = aR; 4. Apbase x = (Apbase)obj; //First your code has some typos. Ignoring that.. I am continuing See carefully. At line 4 we are converting the obj ref to ApBase class. Here obj = aR which is = aBase which is = new ApBase(); So finally obj is actually referring to an object of type ApBase. So at runtime NO ERROR will occur. regds maha anna