File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes About casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "About casting" Watch "About casting" New topic
Author

About casting

Jack Lau
Ranch Hand

Joined: Aug 30, 2002
Posts: 166
Could anyone tell me why runtime error occur ?
Dan Chisholm
Ranch Hand

Joined: Jul 02, 2002
Posts: 1865
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>
Dan Chisholm
Ranch Hand

Joined: Jul 02, 2002
Posts: 1865
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.

Prints: A.s1,B.m1,A.m2
Barkat Mardhani
Ranch Hand

Joined: Aug 05, 2002
Posts: 787
In a line, upcast is legal but downcast is not...
Jack Lau
Ranch Hand

Joined: Aug 30, 2002
Posts: 166
Thank you very much !!
All are very good and easy understanding examples for me.
 
Don't get me started about those stupid light bulbs.
 
subject: About casting