Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting class types 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 "Casting class types" Watch "Casting class types" New topic

Casting class types

koray guclu
Ranch Hand

Joined: Feb 23, 2001
Posts: 59
Suppose we have two classes defined as follows
class ApBase extends Object implements Runnable
class ApBase extends Object implements Runnable
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) Abject 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;
Which statement is true? Can you give me a reasonable
exlanation for type casting of multiple inheritence like as in this example.
Koray G��l�
(B.s. Computer engineer)
Sertification documents and links...

-----------------------------------------------------<BR> Koray GUCLU ~ the sky has no limit ~<BR> (B.s. Computer Engineer)<BR> Frankfurt am Main, Germany<BR> web : <A HREF="<BR rel="nofollow">" TARGET=_blank><BR></A> mail:<BR>-----------------------------------------------------
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13037
That question looks familiar.
The basic rule is that the compiler goes by the type of the variable unless there is an explicit cast.
a) Object obj= aBase;
Runnable rn=obj; // compiler knows Object does not implement Runnable and objects.
b) Object obj= aBase;
Runnable rn=(Runnable)obj; // explicit cast overrides, runtime check performed.

author of:
I agree. Here's the link:
subject: Casting class types
It's not a secret anymore!