Locia said:
Can I cast from base class to derive class?
class A
{
}
class B:A
{
}
A a=new A();
B b=(B) a;
I get a cast exception.
Why?
In simple terms, because inheritance works only from the general
(superclass) to the specific (subclass), not in the reverse direction.
Class B extends class A, thus all B objects are also A objects. However, the
reverse is not true. A objects are not objects of class B.
Giving the classes names makes it clearer. Let's call A Animal and B Mammal.
It's obvious that all mammals are animals, and just as obvious that all
animals are *not* mammals.