Casting
Casting
means to convert from one primitive type to another or from one related class
to another class. (Note: I am using the word convert here, but it is not the
technical sense of the word convert, which is different. See
Type Conversions.)
The syntax for an
explicit cast
uses the new type or class in parentheses before the reference:
intObject = (int) byteObject;
intObject = (int) object.method();
Be careful when casting primitive types.
Even casting to a larger type can result in a loss of precision.
The term promotion refers to casting to a type that
can store a bigger value.
It is safest to make your types match and avoid casting, but sometimes you
will need it or rely on it.
For instance, if you need to add 2 to a real number, but store it in an
int, you would need to cast it.
If you don't use the explicit cast, your code will not compile.
For instance, try writing code that uses this snippet, and then fix it
(you'll need to use a cast ...):
Point p1;
Point p2;
int newX;
newX = p1.getX() + 2;
p2.setLocation(newX, p2.getY());
More on casting and classes later, but here are some highlights:
- You can only cast an object to another class if the two classes are
related by inheritance.
- Casting downward (to a subclass) is automatic. You do not need the
(newClass), although you can use it for clarity if you wish.
- Casting upwards (to a superclass) requires an explicit class and any
additional information that was in the subclass cannot be accessed through
the object on the left-hand side of an assignment.
- The object on the right-hand side can still access these values and
methods because it has not been changed.
You cannot cast a primitive type to a class (or vice-versa).
Java has the Boolean, Byte, Character, Double, Float, Integer, Long
and Short
type-wrapper classes
that correspond to primitive types and allow you to process primitive data as
objects. These can be used for converting.
Converting is not the same as casting. So, for instance, converting a
String to a Double (or double) requires a method call.