File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Reference conversions.... Please help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Reference conversions.... Please help" Watch "Reference conversions.... Please help" New topic

Reference conversions.... Please help

manda prasad

Joined: Oct 06, 2004
Posts: 12
Suppose we have two classes defined as follows:

class ApBase extends Object implements Runnable
class ApDerived extends ApBase implements Observer

Given two variables created as follows:
ApBase aBase = new ApBase() ;
ApDerived aDer = new ApDerived();

Which of the following Java code fragments will compile and execute without error?
a) Object obj = aBase ;
Runnable rn = obj ;

b) Object obj = aBase ;
Runnable rn = (Runnable) obj ;

c) Object obj = aBase ;
Observer ob = (Observer)aBase ;

d) Object obj = aDer ;
Observer ob2 = obj ;

Can anyone please explain what actually is happening in these 4 options...
And which one is the correct option and why ....
And also what is checked in the compile time and runtime..
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Let me try to give you a couple hints and see if you can try to tackle this on your own. If you're still having trouble, come back and let me know.

First of all, remember that you can always use a reference to a child when a reference to a parent is expected. Let's say, for example, you have two classes, Animal and Cat (Cat extends Animal). Anywhere that you would expect to find a reference to an Animal object, you are free to use a Cat object because, after all, a Cat "IS A" Animal. Going the other way does not work. If you're expecting a reference to a Cat object, you can't use a reference to an Animal object because an Animal is not a Cat. So, always keep that rule handy - you can use a child anywhere a parent is expected.

Secondly, downcasting will fail if the run-time type of the object being cast isn't a type of the object you're casting to. So, for example, if you have an Animal object and you try to cast that to a Cat object, you're going to get a ClassCastException, because an Animal is not a Cat. However, if you try to cast a Cat object to an Animal, you're just fine because a Cat is a Animal.

Keep those rules in mind and try to figure out what's happening in each case. Let me know what you come up with.

SCJP Tipline, etc.
I agree. Here's the link:
subject: Reference conversions.... Please help
It's not a secret anymore!