Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 157
instanceof Operator
ОглавлениеThe final relational operator you need to know for the exam is the instanceof
operator, shown in Table 2.8. It is useful for determining whether an arbitrary object is a member of a particular class or interface at runtime.
Why wouldn't you know what class or interface an object is? As we will get into in Chapter 6, “Class Design,” Java supports polymorphism. For now, all you need to know is objects can be passed around using a variety of references. For example, all classes inherit from java.lang.Object
. This means that any instance can be assigned to an Object
reference. For example, how many objects are created and used in the following code snippet?
Integer zooTime = Integer.valueOf(9); Number num = zooTime; Object obj = zooTime;
In this example, only one object is created in memory, but there are three different references to it because Integer
inherits both Number
and Object
. This means that you can call instanceof
on any of these references with three different data types, and it will return true
for each of them.
Where polymorphism often comes into play is when you create a method that takes a data type with many possible subclasses. For example, imagine that we have a function that opens the zoo and prints the time. As input, it takes a Number
as an input parameter.
public void openZoo(Number time) {}
Now, we want the function to add O'clock
to the end of output if the value is a whole number type, such as an Integer
; otherwise, it just prints the value.
public void openZoo(Number time) { if (time instanceof Integer) System.out.print((Integer)time + " O'clock"); else System.out.print(time); }
We now have a method that can intelligently handle both Integer
and other values. A good exercise left for the reader is to add checks for other numeric data types such as Short
, Long
, Double
, and so on.
Notice that we cast the Integer
value in this example. It is common to use casting with instanceof
when working with objects that can be various different types, since casting gives you access to fields available only in the more specific classes. It is considered a good coding practice to use the instanceof
operator prior to casting from one object to a narrower type.
For the exam, you only need to focus on when instanceof
is used with classes and interfaces. Although it can be used with other high-level types, such as records, enums, and annotations, it is not common.