Explaining the instanceof keyword
The instanceof keyword enables us to determine the object type that a reference is referring to. That is why it is so critical to separate the reference from the object. The reference’s type and the object’s type are often very different. In fact, in most cases, they are different. We will discuss instanceof in greater detail when we cover inheritance (Chapter 9) but also when we discuss interfaces (Chapter 10).
So, for the moment, we will keep it simple – where the reference type and object type are the same. Figure 8.26 presents one such code example:
Figure 8.26 – Basic “instanceof” example
In this figure, line 7 creates a Dog object referred to by a Dog reference named dog. Line 8 creates a Cat object referred to by a Cat reference named cat. Line 9 checks if the object at the end of the dog reference is “an instance of” Dog. It is, so line 10 executes. Similarly...