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

Need help on Casting in objects

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,
I am not able to understand the casting procedures with respect to objects.
I have one top level class called citrus which implements sqeezable interface. And 3 subclasses lemon tangelo & grapefruit
In the following code
grapefruit g,g1;
citrus c;
tangelo t;
g=new grapefruit();
c=g;
g1=(grapefruit)c;//legal (1)
t=(tangelo)c//illegal. (2)
Its' confusing why statment 1 is legal and 2 is illegal(This is given in R& H).
Please help me out.
Thanks & regards
Ananth

 
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It is because when you initialized c, you set it to a grapefruit, with that statement c = g; Since c is really a grapefruit, you can cast it back down to a grapefruit object g1. But since c was never a tengelo, you can't cast it back down to something it never was.
 
Anantha Krishna
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Bill,
One more clarification. Is it possible to again reassign c to t
like this.
Tangelo t1
c=t;
and then do
t1=(tangelo)c
Thanks and regards
Ananth
 
bill bozeman
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Try it out and tell me what you get.
 
Anantha Krishna
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
It's working.
Thank you bill
Ananth
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic