| Author |
Please explain DownCast Code from K&B
|
Srinivas Katta
Ranch Hand
Joined: Feb 01, 2007
Posts: 74
|
|
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
Joined: Jun 25, 2010
Posts: 41
|
|
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
Joined: Feb 01, 2007
Posts: 74
|
|
|
Thanks for the explanation. that cleared my query on references
|
 |
 |
|
|
subject: Please explain DownCast Code from K&B
|
|
|