The following code example demonstrates why a base class can not be cast to a sub class.
A sub class is more specialized than a base class. Since the base class does not have the specialized behavior of the sub class it is not possible to cast an instance of a base class to a sub class type.
Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>
Joined: Jul 02, 2002
It is important to remember that when you cast an instance of an object from one type to another the object instance is not modified in any way. Instead, the only thing that changes is the view of the object. For example, when a subclass such as Dog is cast to the base class, Pet, the view of the Dog instance is narrowed to a Pet base class view. A reference of type Pet can only access the members of the Dog subclass that are declared in the Pet base class.
Of course, the rules of member inheritance and hiding apply as demonstrated by the following code.