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 Interface and Casting 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 "Interface and Casting" Watch "Interface and Casting" New topic

Interface and Casting

Lakshmi Saradha
Ranch Hand

Joined: Oct 21, 2003
Posts: 170
I came acroos this questions in Brogden's site.
import java.util.*;
class ApBase extends Object implements Runnable{public void run() {}}
class ApDerived extends ApBase implements Observer {public void update(Observable o,Object arg ) {}}
class A {
public static void main (String args[]) {
ApBase abase = new ApBase();
ApDerived ader = new ApDerived();
The question was 'Which of teh following will compile and execute without error?'
The options given are:
1)Object obj = abase;
Runnable rn = obj;
2) Object obj = abase;
Runnable rn = (Runnable)obj;
3)Object obj = abase;
Observer ob = (Observer)abase;
4)Object obj= ader;
Observer o = obj.
The correct ans is b). I understood that 1) is a wrong option.

Could you help me in finding out why b) is right and why c) and d) are wrong?
Also could any one sugegst a good reading material on this topic?

I am totally lost

Thanks,<br />Lakshmi.
Ray Stojonic
Ranch Hand

Joined: Aug 08, 2003
Posts: 326
Hi Lakshmi,
2 is correct because:
Object obj = abase;
abase is a ApBase reference to an ApBase object, which is extended from Object, this is a widening assignment, no cast required.
Runnable rn = (Runnable)obj;
obj is an Object reference to an ApBase object, which implements Runnable, this is a narrowing assignment, implicit cast required. At compile time it is assumed that the cast will be valid. At runtime, the cast is valid, no error.
3 is wrong because:
Object obj = abase;
This is fine, as above
Observer ob = (Observer)abase;
abase is an ApBase reference to an ApBase object, class ApBase has nothing to do with Observer. Observer is an interface, so it's assumed at compile time that the object referred to by abase will be able to be cast to an Observer object, compiles fine. At runtime this is found to not be the case, ClassCastException occurs.
4 is wrong because:
Object obj= ader;
This is fine, as above, but with ApDerived object
Observer o = obj.
Object to Observer is a narrowing assignment, implicit cast required.

hope that helps
Lakshmi Saradha
Ranch Hand

Joined: Oct 21, 2003
Posts: 170
Thank you Ray.
I agree. Here's the link:
subject: Interface and Casting
It's not a secret anymore!