Java Reference
In-Depth Information
This statement will throw a
ClassCastException
because
name
points to an object of
the
class
Person
. It does not refer to an object of the
class
PartTimeEmployee
.
However, the following statement is legal:
employeeRef = (PartTimeEmployee) nameRef;
Because
nameRef
refers to the object
employee
(as set by the statement in Line 5), and
employee
is a reference variable of the
PartTimeEmployee
type, this statement would
make
employeeRef
point to the object
employee
. Therefore, the output of the statement:
System.out.println(employeeRef);
is:
Susan Johnson's wages are: $562.50
As previously described, an object of a subclass type can be considered an object of the
superclass type. Moreover, by using an appropriate cast operator, you can treat an object of
a superclass type as an object of a subclass type. To determine whether a reference variable
that points to an object is of a particular class type, Java provides the operator
instanceof
.
Consider the following expression (suppose that
p
is an object of a class type):
p
instanceof
BoxShape
This expression evaluates to
true
if
p
points to an object of the
class
BoxShape
;
otherwise, it evaluates to
false
. The
class
BoxShape
is defined in Example 10-6,
which further illustrates how the operator
instanceof
works.
EXAMPLE 10-6
Consider the following classes: (The
class
es
RectangleShape
and
BoxShape
are the same
as the
class
es
Rectangle
and
Box
given earlier in this chapter. The only difference is that
the instance variables of the
class
es
Rectangle
and
Box
are
private
. Because the instance
variables of the
class
RectangleShape
are
protected
, they can be directly accessed in
the
class
BoxShape
. Therefore, the definitions of the methods
area
and
volume
of the
class
BoxShape
directly access the instance variables
length
and
width
of the
class
RectangleShape
.)
public class
RectangleShape
{
protected double
length;
protected double
width;
public
RectangleShape()
{
length = 0;
width = 0;
}
Search WWH ::
Custom Search