• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

casting

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
Thanx
Sonali
 
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
Cheers
Tejas Kansara
 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic