This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Mock Exam Errata and the fly likes casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Mock Exam Errata
Bookmark "casting" Watch "casting" New topic


sonali saxena

Joined: Mar 18, 2001
Posts: 16
class Parent {}
class DerivedOne extends Parent {}
class DerivedTwo extends Parent {}

Which of the following statements is correct for the following expression?
Parent p = new Parent();
DerivedOne d1 = new DerivedOne();
DerivedTwo d2 = new DerivedTwo();
d2 = d1;

A. Illegal both at compile and runtime.
B. Legal at compile time, but may fail at runtime.
C. Legal at both compile and runtime.
The answer given is 'b' but according to me it is 'a'. Am I wrong?
Tejas Kansara
Ranch Hand

Joined: Dec 14, 2000
Posts: 38
According to me it is 'a'
bcoz you cannot type cast one derived to other derived instead you can cast from derived to base class.
Tejas Kansara
Umesh Joglekar

Joined: May 02, 2001
Posts: 16
A is correct. It will not compile. It will also not compile with an explicit cast i.e. d2 = (DerivedTwo) d1 because d1 is not convertible to d2 even with a cast.
subject: casting
It's not a secret anymore!