posted 24 years ago
Hi everyone,
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.
Any thought is appreciated.
------------------