Java Reference
In-Depth Information
example we used a widening cast in
printName
to convert the type of
this
to its superclass type:
Base sref = (Base) this;
This cast was unnecessary but emphasized that we really wanted the
current object to be treated as an instance of its superclass. If we then
try to assign
sref
back to a reference of the narrower
More
type, an ex-
plicit cast is essential:
More mref = (More) sref;
Even though we know the object referred to is of the right type, the
compiler still requires an explicit cast.
A widening conversion is also known as an
upcast
because it casts from
one type to another further up the type hierarchyit is also a
safe cast
because it is always valid. A narrowing conversion is also known as a
downcast
because it casts from one type to another, further down the
inheritance hierarchyit is also an
unsafe cast
because it may not be val-
id.
When a cast is used to request a conversion, the compiler does not as-
sume that the conversion is correct. If the compiler can tell that is cast
is correct, then it can apply the cast. If the compiler can tell that a cast
is incorrect then a compile time error can occur. If the compiler cannot
ascertain that the cast is correct at compile time, then a run time check
will be performed. If the run time check fails because the cast is incor-
rect, then a
ClassCastException
is thrown.
3.4.3. Testing for Type
You can test the class of an object by using the
instanceof
operator,
which evaluates to
true
if the expression on its left is a reference type