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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.