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

Interface cast

Krishna Priya

Joined: Jun 08, 2000
Posts: 5
Hi All,
I have one query regarding innterface cast.This is from one of the mocks.
Suppose we have 2 classes defined as follows:
class base extends object implements Runnable
class derived extends base implements Observer
Given 2 variables created as follows:
base abase = new base();
derived ader=new derived();
which of the following java statements will compile and
execute without error.choose all which apply.
A.Runnable rn=ader;
B.Runnable rn2=(Runnable)abase;
C.Observer ob=abase;
D.Observer ob2=(Observer)abase;
Answers given was a and b.
But I didn't understood the interface cast.Could any of you please explain me how it is?
Thanks and Regards
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
Hi Krishna,
I think I can explain this (someone correct me if I get it wrong).
a. will work as derived class implements Runnable thru it's super
class base
b. will work as 'abase' class 'base' implements Runnable
c. will not work as 'abase' class 'base' does not implement
d. will not work for same reason as 'c'; the cast might work at
compile time but error will occur at runtime.
Basic rule is that you can assign 'up' the inheritance chain ie from derived to base but not vice versa.
Hope that helps.

Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
Ranch Hand

Joined: Oct 20, 2000
Posts: 68
base abase = new base();
derived ader=new derived();

First of all there is no need for casting in

(B) Runnable rn2=(Runnable)abase; //OK

both Runnable rn2=(Runnable)abase; & Runnable rn2 = base; are same

The program will compile and run without any problem even
if you give as below

Runnable rn2 = base;

" class Base extends Object implements Runnable"

The above code implies that base is sub class and
Object & Runnable are Super. Hence the followings are true

Runnable rn2 = abase; //For Upward no casting is needed
Object o = abase; // do

Runnable rn=ader; //OK

The super classes of Derived class are
Base, Observer, Runnable (Due to Base)

(C) Observer ob=abase; // NOT OK no relation beteween
// Base & Observer

(D) Observer ob2=(Observer)abase; // NOT OK as above
// here because of (Observer) casting , the
// code compiles happily. But during run time
//ClassCastException will be thrown, since during
// runtime only object type is checked


I agree. Here's the link:
subject: Interface cast
It's not a secret anymore!