Q. Why this code compile OK, but throw ClassCastException at run time?
Base b=new Base();
Sub s=new Sub(); //Sub extends Base
s=(Sub)b;
A:
"Oversea Chinese is a Chinese", but not vise versa.
"Chinese is not necessary an oversea Chinese, but possible."
When you cast super to sub, compiler assume that you know what you were
doing, since it is possible. However, runtime will find out b actually is not a Sub.
Since Cat is an Animal, but Animal is not necessary a Cat, but it is possible a Cat.
That is why downcast is allowed on compile time, since compiler assumes you
know what you are doing. However, Runtime will find out this Animal is actually
not a Cat.
ClassCastException! Big time.
Base b=new Base();
Sub s=new Sub(); //Sub extends Base
s=(Sub)b;
A:
"Oversea Chinese is a Chinese", but not vise versa.
"Chinese is not necessary an oversea Chinese, but possible."
When you cast super to sub, compiler assume that you know what you were
doing, since it is possible. However, runtime will find out b actually is not a Sub.
Since Cat is an Animal, but Animal is not necessary a Cat, but it is possible a Cat.
That is why downcast is allowed on compile time, since compiler assumes you
know what you are doing. However, Runtime will find out this Animal is actually
not a Cat.
ClassCastException! Big time.