wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting - Confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting - Confusion" Watch "Casting - Confusion" New topic
Author

Casting - Confusion

Supree
Greenhorn

Joined: Feb 25, 2000
Posts: 27
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.

------------------
maha anna
Ranch Hand

Joined: Jan 31, 2000
Posts: 1467
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
Supree
Greenhorn

Joined: Feb 25, 2000
Posts: 27
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
maha anna
Ranch Hand

Joined: Jan 31, 2000
Posts: 1467
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Casting - Confusion
 
Similar Threads
type casting
A suggestion for list of Mock Questions
Casting
casting
Question on casting