Java Reference
In-Depth Information
if (anObject instanceof BankAccount)
{
BankAccount anAccount = (BankAccount) anObject;
. . .
}
The
instanceof
operator tests whether an object belongs to a particular type.
S
YNTAX
10.4 The
instanceof
Operator
object
instanceof
TypeName
Example:
if (anObject instanceof BankAccount)
{
BankAccount anAccount = (BankAccount) anObject;
. . .
}
Purpose:
To return
true
if the object is an instance of TypeName (or one of its subtypes),
and
false
otherwise
S
ELF
C
HECK
10.
Why did the second parameter of the
transfer
method have to be of
type
BankAccount
and not, for example,
SavingsAccount
?
11.
Why can't we change the second parameter of the
transfer
method to
the type
Object
?
454
455
10.6 Polymorphism
In Java, the type of a variable does not completely determine the type of the object to
which it refers. For example, a variable of type
BankAccount
can hold a reference
to an actual
BankAccount
object or a subclass object such as
SavingsAccount
.
You already encountered this phenomenon in
Chapter 9
with variables whose type
was an interface. A variable whose type is
Measurable
holds a reference to an