instanceof UseUse the instanceof operator on a class instance to determine if it can be cast to a derived class.
This page was last reviewed on Jan 20, 2024.
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.
Example. 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.
Part 1 We create an instance of Program with the new operator, but refer to this as an Object. The instanceof operator then returns true.
Part 2 Here we refer to an ArrayList of Strings as an object, and the instanceof operator also matches the ArrayList class.
Part 3 It is possible to get an instance of the type we tested for—here we have a 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
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 20, 2024 (new).
© 2007-2024 Sam Allen.