Java Reference
In-Depth Information
moved, then the call
Superhero.memberCount()
will result in error. The reason is that the
Superhero
class will now not contain the method and Java will not check the superclass.
The reason is that polymorphism does not apply to methods of type
static
.
8.11 Explicit Type Checking
Let us continue our superhero and villain example. Suppose that we have created several
superheroes and villains and have added them to the single
ArrayList characters
.
ArrayList
<
FictionalCharacter
>
characters =
new
ArrayList
<>
() ;
...
Suppose that now we want to count the number of superheroes and the number of
villains in the
ArrayList
. We can call the
memberCount
method that was described in the
previous section. However, this method will give us the total number of superheroes and
not the number of superheroes in the
ArrayList
. Note that in the
ArrayList
we have a
number of objects of type
FictionalCharacter
. However, since the
FictionalCharacter
class is abstract, these objects must belong to its subclasses. Therefore, we need a way to
determine the type of an object. One way of performing this task is using the
instanceof
keyword. Here is an example.
int
count = 0;
for
(FictionalCharacter el : characters)
{
if
(el
instanceof
Superhero)
{
count++;
}
}
The
instanceof
keyword checks if the object belongs to the class. It returns
true
if it does
and
false
otherwise. The above code iterates through all the elements of the
ArrayList
.
If an element belongs to the
Superhero
class, then the counter is incremented by one. The
code computes the number of superheroes in the
ArrayList
.
The expression
o instanceof C
returns
true
exactly when the
o
object is an
instance of the
C
class or one of its descendents in the inheritance hierarchy.
Note that the code:
el instance of FictionalCharacter
will be true for all the ele-
ments
el
of the
ArrayList
.
Alternatively, one can use the
getClass
method to determine the type of an object. The
method returns the class of an object. Here is an example.
for
(FictionalCharacter el : characters)
{
if
( el . getClass ()==Superhero .
class
)
{
count++;
}
}
The
getClass
method is defined in the
Object
class. In other words, it can be called
on any object. It returns the runtime type of the object.