// primitive converting cast short s = (short) someInt;would convert to a short integer.
// mollifying cast Dalmatian d = (Dalmatian) dog;assures Java that the dogRef pointer really points to a Dalmatian. Java checks that this is indeed so before proceeding. Casting objects is a misleading terminology. Any actual object has a definite class, set when it was instantiated. Nothing can change that during the lifetime of the object. The object it self is unchanged when you cast its reference.
In the days before generics, casts were most needed after you retrieved an element from a Collection. The collection just gave you a generic Object, but you knew better what it was, since you knew what sort of Objects you put into the collection.
If a mollifying downcast fails, because the object is not really what you tried to cast it to, you will get a ClassCastException. Upcasts always succeed. Upcasts are always unnecessay.Before you cast, you can use instanceof, or one of its brothers, to check if a cast will work.
![]() |
and suggestions to improve this page to Roedy Green : | ||
| Canadian Mind Products | |||
| mindprod.com IP:[65.110.21.43] | |||
| Your face IP:[38.103.63.18] | The information on this page is for non-military use only. | ||
| You are visitor number 23,608. | Military use includes use by defence contractors. | ||
| You can get a fresh copy of this page from: | or possibly from your local J: drive (Java virtual drive/Mindprod website mirror) | ||
| http://mindprod.com/jgloss/cast.html | J:\mindprod\jgloss\cast.html | ||