A Child
class instance can be cast to Parent
class reference, because since Child
inherits Parent
, Child
should support all behaviors which Parent
already supported.
Example
class Parent {
public void getA() {
return 1;
}
}
class Child extends Parent {
public void getB() {
return 1;
}
}
Now lets consider 2 objects
Child c = new Child();
Parent p = new Parent();
Now if you do
Parent p2 = (Parent) c;
this is valid, because when you invoke p2.getA()
, it will work since getA()
method is already inherited by c
which is instance of Child
.
Now if you do
Child c2 = (Parent) p;
this will not work because, the type of c2
is Child
, and the call c2.getB()
is valid. But since the instance p
is of type Parent
, it doesn't have implementation to getB()
(which was the new method added down in the inheritance by child class).
In simple terms inheritance is an IS A relationship
Coming back to your problem
A Redwood
IS A Tree
so Tree t = (Tree) (new Redwood());
works. This means a Redwood
instance can be cast to Tree
But a Tree
is NOT A Reedwood
always (it can be anything).. so Redwood r = (Redwood) new Tree()
doesn't work