Java Reference
In-Depth Information
A character can be used as an
int
because each character has a
corresponding numeric code that represents its position in the
character set. If the variable
i
has the value
65
, the cast
(char)i
produces the character value
A
. The numeric code associated with
a capital A is 65, according to the ASCII character set, and Java
adopted this as part of its character support.
NOTE
You must use an explicit cast to convert a value in a large type to a smaller type, or else
converting that value might result in a loss of precision. Explicit casts take the following
form:
(
typename
)
value
In the preceding example,
typename
is the name of the data type to which you're con-
verting, such as
short
,
int
, or
float
.
value
is an expression that results in the value of
the source type. For example, in the following statement, the value of
x
is divided by the
value of
y
, and the result is cast into an
int
in the following expression:
int result = (int)(x / y);
Note that because the precedence of casting is higher than that of arithmetic, you have to
use parentheses here; otherwise, the value of
x
would be cast into an
int
first and then
divided by
y
, which could easily produce a different result.
Casting Objects
Instances of classes also can be cast into instances of other classes, with one restriction:
The source and destination classes must be related by inheritance; one class must be a
subclass of the other.
Some objects might not need to be cast explicitly. In particular, because a subclass con-
tains all the same information as its superclass, you can use an instance of a subclass
anywhere a superclass is expected.
For example, consider a method that takes two arguments, one of type
Object
and
another of type
Component
. You can pass an instance of any class for the
Object
argu-
ment because all Java classes are subclasses of
Object
. For the
Component
argument, you
can pass in its subclasses, such as
Button
,
Container
, and
Label
.
This is true anywhere in a program, not just inside method calls. If you had a variable
defined as class
Component
, you could assign objects of that class or any of its subclasses
to that variable without casting.