Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please explain DownCast Code from K&B

 
Srinivas Katta
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • 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
 
Chad Michaels
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Thanks for the explanation. that cleared my query on references
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic