• 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Please explain DownCast Code from K&B

 
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

I have executed the below Code

public class Redwood extends Tree {
public static void main(String[] args) {
new Redwood().go();
}
void go() {
go2(new Tree(), new Redwood());
go2((Redwood) new Tree(), new Redwood());
}
void go2(Tree t1, Redwood r1) {
Redwood r2 = (Redwood)t1; //Line 10
Tree t2 = (Tree)r1;
}
}

class Tree { }

I am getting ClassCastException at Lien 10 saying that Tree cannot be cast to Redwood, But as I understand Redwood is a subclass of Tree so it is downcast to Tree

Can somebody explain why this downcast is throwing Classcast Exception

Thanks
Srinivas
 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, That's right, a Tree cannot be a Redwood; although, a Redwood can be a Tree.

Not sure where "line 10" is in your example... but see if this clears is up for you. It's all about the references.

Tree t = new Tree( ) can never be downcast to a Redwood.
Tree tr = new Redwood( ) can be downcast to a Redwood.

See why?

Remember, the object never changes, but it's "references" do. And object is an object is an object. A Tree will always be a Tree. A Redwood will always be a Redwood. You can't change that. You can only change the references.

Hope I'm not wrong, but that's how I see it.
 
Srinivas Katta
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for the explanation. that cleared my query on references
 
I've been selected to go to the moon! All thanks to this tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic