There are two useful kinds of casts.
// primitive converting cast short s = (short) someInt;would convert to a short integer. Converting casts come is two flavours narrowing and widening. Narrowing casts such as (int) someLong generally reduce the number of bits in the representation. They are mandatory. Widening casts such as (long) someInt generally increase the number of bits in the representation. They are optional. Casts you can leave out include: byte → int, char → int, short → int, int → long, int → float, int → double, long → double. You don’t need an explict cast for long → double, even though you can sometimes lose some low order bits of precision.
// 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. If it is not a Dalmatian (or subclass of Dalmatian) as you claimed, it throws a CastClassException. It has no way to fix the problem by somehow converting the Object to a Dalmatian.
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. Now the explicit casts are no longer needed. Javac.exe transparently inserts any needed checkcast JVM (Java Virtual Machine) instructions in the generated code.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.
This page is posted
Optional Replicator mirror
|no blog for this page||Canadian
Your face IP:[220.127.116.11]
You are visitor number|