Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Casting class types

 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
QUESTION:
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.
Thanks.
----------------------------------
Koray G��l�
(B.s. Computer engineer)
http://www.geocities.com/korayguclu/
Sertification documents and links...
----------------------------------
 
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Bill

------------------
author of:
    Bookmark Topic Watch Topic
  • New Topic