AI Features

InstanceOf Operators

Learn about the instanceOf operator with the help of an example in this lesson.

These operators check whether an object is an instance of a class or a subclass. If a class implements an interface, that can also be checked.

Coding example: 53

Let us see the following example to understand how it works:

Java
/*
You can use the instanceof operator to test if an object is an instance of a class,
an instance of a subclass, or an instance of a class that implements a particular interface
*/
interface PlaceTheOrder{
public void place();
}
class ParentClass implements PlaceTheOrder{
public void place(){
System.out.println("Placing the order.");
}
}
class ChildClass extends ParentClass{
}
public class ExampleFiftyThree {
public static void main(String[] args) {
ParentClass parent = new ParentClass();
ChildClass child = new ChildClass();
/*
The following two questions will have answers true
*/
System.out.println("Is parent instance of ParentClass? : " + (parent instanceof ParentClass));
System.out.println("Is parent instance of interface PlaceTheOrder? : " + (parent instanceof PlaceTheOrder));
//it is false
System.out.println("Is parent instance of ChildClass? : " + (parent instanceof ChildClass));
/*
The following answers will be true, because ChildClass is a subclass of ParentClass
*/
System.out.println("Is child instance of ChildClass? : " + (child instanceof ChildClass));
System.out.println("Is child instance of ParentClass? : " + (child instanceof ParentClass));
System.out.println("Is child instance of interface PlaceTheOrder? : " + (child instanceof PlaceTheOrder));
}
}

Code explanation

As you see in the above code, there are two classes and one interface. One is the parent class, and one is the child class. The ...