Win a copy of Testing JavaScript Applications this week in the HTML Pages with CSS and JavaScript 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 ...
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Reference conversions.... Please help

Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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..
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
    Bookmark Topic Watch Topic
  • New Topic