InstanceOf
Is a variable an instance of a class
? If we have a variable of a base class
like Object, we can determine what the derived class
is with instanceof
.
And with instanceof
, we can get avoid casting directly and simply access a variable of the derived class
we tested for. This can lead to cleaner Java code.
We have a class
Program
that is declared in this Java program. Because Program
is a class
, it is derived automatically from Object, the ultimate base class
.
Program
with the new operator, but refer to this as an Object. The instanceof
operator then returns true.ArrayList
of Strings as an object, and the instanceof
operator also matches the ArrayList
class
.String
, and we get a String
from instanceof
.public class Program { public static void main(String[] args) { // Part 1: create an instance of a class and refer to it by a base class Object. Object value = new Program(); if (value instanceof Program) { System.out.println("Object is instanceof Program"); } // Part 2: use instanceof with a type parameter. Object value2 = new java.util.ArrayList<String>(); if (value2 instanceof java.util.ArrayList) { System.out.println("ArrayList"); } // Part 3: use instanceof and declare a name for the result of the cast. Object value3 = new String("bird"); if (value3 instanceof String s) { System.out.println("String = " + s); } } }Object is instanceof Program ArrayList String = bird
With instanceof
in Java, we can test is a variable can be cast to another type. And we can even store the cast variable and use it later in our code.