• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Casting

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The following defines an object hierarchy.
class class1{}
class class2 extends class1 {}
class class3 extends class2 {}
1. when is the following method valid?
public class3 castMe(class1 ref) {
return (class3)ref;
}
a) always
b) never
c)if and only if ref references an class3 object
d) if and only if ref references an class2 object
The given answer is c. I cannot understand why it is c. Can some body explain...?
Thanks
 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

There can be three ways in which castMe can be called. Let us see how each will react.
1. If you pass an instance of C1 then the method will try to cast into C3 this will give you a ClassCastException since java does not support downcasting.
2. If you pass an instance of C2 then the same message as in C1.
3. If you pass an instance of C3 that will go through.
So (c) is the only answer for your question.
 
devi nachimuthu
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I agree with you sachin, but how can i pass C1 to C3. There is no relation between Class1 and Class3, Class3 is inheriting from Class2. So how can we pass C1 to C3...?
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic