How to Check If an Object Is an Instance of a Class in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if an object is an instance of a specific class or interface in Java using the instanceof keyword. We will explore its basic usage, test its behavior with subclasses, and understand how it handles null objects.

Through hands-on examples, you will gain practical experience in using instanceof to perform runtime type checking, a fundamental concept in object-oriented programming.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("Classes/Objects") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("OOP") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/inheritance("Inheritance") subgraph Lab Skills java/if_else -.-> lab-560010{{"How to Check If an Object Is an Instance of a Class in Java"}} java/classes_objects -.-> lab-560010{{"How to Check If an Object Is an Instance of a Class in Java"}} java/oop -.-> lab-560010{{"How to Check If an Object Is an Instance of a Class in Java"}} java/inheritance -.-> lab-560010{{"How to Check If an Object Is an Instance of a Class in Java"}} end

Use instanceof for Class Check

In this step, we will explore the instanceof keyword in Java. The instanceof keyword is used to test whether an object is an instance of a particular class or implements a particular interface. It's a useful tool for checking the type of an object at runtime.

Let's create a simple Java program to demonstrate how instanceof works.

  1. Open the WebIDE and make sure you are in the ~/project directory. You can confirm this by looking at the terminal prompt or by typing pwd and pressing Enter.

  2. Create a new Java file named TypeCheck.java in the ~/project directory. You can do this by right-clicking in the File Explorer on the left and selecting "New File", then typing TypeCheck.java.

  3. Open the TypeCheck.java file in the editor and paste the following code:

    class Animal {
        // Base class
    }
    
    class Dog extends Animal {
        // Subclass of Animal
    }
    
    class Cat extends Animal {
        // Subclass of Animal
    }
    
    public class TypeCheck {
        public static void main(String[] args) {
            Animal myAnimal = new Dog();
    
            // Check if myAnimal is an instance of Dog
            if (myAnimal instanceof Dog) {
                System.out.println("myAnimal is an instance of Dog");
            } else {
                System.out.println("myAnimal is not an instance of Dog");
            }
    
            // Check if myAnimal is an instance of Cat
            if (myAnimal instanceof Cat) {
                System.out.println("myAnimal is an instance of Cat");
            } else {
                System.out.println("myAnimal is not an instance of Cat");
            }
    
            // Check if myAnimal is an instance of Animal
            if (myAnimal instanceof Animal) {
                System.out.println("myAnimal is an instance of Animal");
            } else {
                System.out.println("myAnimal is not an instance of Animal");
            }
        }
    }

    In this code:

    • We define a base class Animal and two subclasses Dog and Cat.
    • In the main method, we create an Animal variable myAnimal and assign a Dog object to it. This is possible because a Dog is a type of Animal.
    • We then use the instanceof keyword to check if myAnimal is an instance of Dog, Cat, and Animal.
  4. Save the TypeCheck.java file (Ctrl+S or Cmd+S).

  5. Compile the Java program by opening the terminal at the bottom of the WebIDE and running the following command:

    javac TypeCheck.java

    If there are no errors, this command will create a TypeCheck.class, Animal.class, Dog.class, and Cat.class file in the ~/project directory.

  6. Run the compiled program using the following command:

    java TypeCheck

    You should see output similar to this:

    myAnimal is an instance of Dog
    myAnimal is not an instance of Cat
    myAnimal is an instance of Animal

    This output confirms that myAnimal, which holds a Dog object, is indeed an instance of Dog and also an instance of its superclass Animal, but not an instance of Cat.

You have successfully used the instanceof keyword to check the type of an object in Java. In the next step, we will explore how instanceof behaves with subclasses.

Test with Subclasses

In the previous step, we saw that an object is considered an instance of its own class and also an instance of its superclass. Let's further explore how instanceof works with different object types and their subclasses.

We will modify our existing TypeCheck.java file to test instanceof with a Cat object.

  1. Open the TypeCheck.java file in the WebIDE editor.

  2. Locate the main method and add the following lines of code after the existing checks for myAnimal:

            System.out.println("\n--- Testing with a Cat object ---");
            Animal anotherAnimal = new Cat();
    
            // Check if anotherAnimal is an instance of Dog
            if (anotherAnimal instanceof Dog) {
                System.out.println("anotherAnimal is an instance of Dog");
            } else {
                System.out.println("anotherAnimal is not an instance of Dog");
            }
    
            // Check if anotherAnimal is an instance of Cat
            if (anotherAnimal instanceof Cat) {
                System.out.println("anotherAnimal is an instance of Cat");
            } else {
                System.out.println("anotherAnimal is not an instance of Cat");
            }
    
            // Check if anotherAnimal is an instance of Animal
            if (anotherAnimal instanceof Animal) {
                System.out.println("anotherAnimal is an instance of Animal");
            } else {
                System.out.println("anotherAnimal is not an instance of Animal");
            }

    Your complete TypeCheck.java file should now look like this:

    class Animal {
        // Base class
    }
    
    class Dog extends Animal {
        // Subclass of Animal
    }
    
    class Cat extends Animal {
        // Subclass of Animal
    }
    
    public class TypeCheck {
        public static void main(String[] args) {
            Animal myAnimal = new Dog();
    
            // Check if myAnimal is an instance of Dog
            if (myAnimal instanceof Dog) {
                System.out.println("myAnimal is an instance of Dog");
            } else {
                System.out.println("myAnimal is not an instance of Dog");
            }
    
            // Check if myAnimal is an instance of Cat
            if (myAnimal instanceof Cat) {
                System.out.println("myAnimal is an instance of Cat");
            } else {
                System.out.println("myAnimal is not an instance of Cat");
            }
    
            // Check if myAnimal is an instance of Animal
            if (myAnimal instanceof Animal) {
                System.out.println("myAnimal is an instance of Animal");
            } else {
                System.out.println("myAnimal is not an instance of Animal");
            }
    
            System.out.println("\n--- Testing with a Cat object ---");
            Animal anotherAnimal = new Cat();
    
            // Check if anotherAnimal is an instance of Dog
            if (anotherAnimal instanceof Dog) {
                System.out.println("anotherAnimal is an instance of Dog");
            } else {
                System.out.println("anotherAnimal is not an instance of Dog");
            }
    
            // Check if anotherAnimal is an instance of Cat
            if (anotherAnimal instanceof Cat) {
                System.out.println("anotherAnimal is an instance of Cat");
            } else {
                System.out.println("anotherAnimal is not an instance of Cat");
            }
    
            // Check if anotherAnimal is an instance of Animal
            if (anotherAnimal instanceof Animal) {
                System.out.println("anotherAnimal is an instance of Animal");
            } else {
                System.out.println("anotherAnimal is not an instance of Animal");
            }
        }
    }
  3. Save the modified TypeCheck.java file.

  4. Compile the program again in the terminal:

    javac TypeCheck.java
  5. Run the compiled program:

    java TypeCheck

    You should now see output similar to this:

    myAnimal is an instance of Dog
    myAnimal is not an instance of Cat
    myAnimal is an instance of Animal
    
    --- Testing with a Cat object ---
    anotherAnimal is not an instance of Dog
    anotherAnimal is an instance of Cat
    anotherAnimal is an instance of Animal

    This output shows that anotherAnimal, which holds a Cat object, is an instance of Cat and Animal, but not Dog. This reinforces the concept that instanceof checks the actual type of the object and its inheritance hierarchy.

You have successfully tested the instanceof keyword with different subclass objects. In the next step, we will see how instanceof behaves with null objects.

Verify with Null Objects

In this final step, we will investigate how the instanceof keyword behaves when the object being tested is null. Understanding this is important to avoid potential errors in your Java programs.

We will again modify our TypeCheck.java file to include a test with a null object.

  1. Open the TypeCheck.java file in the WebIDE editor.

  2. Add the following lines of code at the end of the main method, after the previous tests:

            System.out.println("\n--- Testing with a null object ---");
            Animal nullAnimal = null;
    
            // Check if nullAnimal is an instance of Dog
            if (nullAnimal instanceof Dog) {
                System.out.println("nullAnimal is an instance of Dog");
            } else {
                System.out.println("nullAnimal is not an instance of Dog");
            }
    
            // Check if nullAnimal is an instance of Animal
            if (nullAnimal instanceof Animal) {
                System.out.println("nullAnimal is an instance of Animal");
            } else {
                System.out.println("nullAnimal is not an instance of Animal");
            }

    Your complete TypeCheck.java file should now look like this:

    class Animal {
        // Base class
    }
    
    class Dog extends Animal {
        // Subclass of Animal
    }
    
    class Cat extends Animal {
        // Subclass of Animal
    }
    
    public class TypeCheck {
        public static void main(String[] args) {
            Animal myAnimal = new Dog();
    
            // Check if myAnimal is an instance of Dog
            if (myAnimal instanceof Dog) {
                System.out.println("myAnimal is an instance of Dog");
            } else {
                System.out.println("myAnimal is not an instance of Dog");
            }
    
            // Check if myAnimal is an instance of Cat
            if (myAnimal instanceof Cat) {
                System.out.println("myAnimal is not an instance of Cat");
            } else {
                System.out.println("myAnimal is not an instance of Cat");
            }
    
            // Check if myAnimal is an instance of Animal
            if (myAnimal instanceof Animal) {
                System.out.println("myAnimal is an instance of Animal");
            } else {
                System.out.println("myAnimal is not an instance of Animal");
            }
    
            System.out.println("\n--- Testing with a Cat object ---");
            Animal anotherAnimal = new Cat();
    
            // Check if anotherAnimal is an instance of Dog
            if (anotherAnimal instanceof Dog) {
                System.out.println("anotherAnimal is not an instance of Dog");
            } else {
                System.out.println("anotherAnimal is not an instance of Dog");
            }
    
            // Check if anotherAnimal is an instance of Cat
            if (anotherAnimal instanceof Cat) {
                System.out.println("anotherAnimal is an instance of Cat");
            } else {
                System.out.println("anotherAnimal is an instance of Cat");
            }
    
            // Check if anotherAnimal is an instance of Animal
            if (anotherAnimal instanceof Animal) {
                System.out.println("anotherAnimal is an instance of Animal");
            } else {
                System.out.println("anotherAnimal is an instance of Animal");
            }
    
            System.out.println("\n--- Testing with a null object ---");
            Animal nullAnimal = null;
    
            // Check if nullAnimal is an instance of Dog
            if (nullAnimal instanceof Dog) {
                System.out.println("nullAnimal is an instance of Dog");
            } else {
                System.out.println("nullAnimal is not an instance of Dog");
            }
    
            // Check if nullAnimal is an instance of Animal
            if (nullAnimal instanceof Animal) {
                System.out.println("nullAnimal is an instance of Animal");
            } else {
                System.out.println("nullAnimal is not an instance of Animal");
            }
        }
    }
  3. Save the modified TypeCheck.java file.

  4. Compile the program in the terminal:

    javac TypeCheck.java
  5. Run the compiled program:

    java TypeCheck

    You should see output similar to this:

    myAnimal is an instance of Dog
    myAnimal is not an instance of Cat
    myAnimal is an instance of Animal
    
    --- Testing with a Cat object ---
    anotherAnimal is not an instance of Dog
    anotherAnimal is an instance of Cat
    anotherAnimal is an instance of Animal
    
    --- Testing with a null object ---
    nullAnimal is not an instance of Dog
    nullAnimal is not an instance of Animal

    As you can see from the output, when the object being tested with instanceof is null, the result is always false. This is a crucial point to remember when using instanceof to avoid unexpected behavior or NullPointerExceptions.

You have successfully verified how the instanceof keyword behaves with null objects. This concludes our exploration of the instanceof keyword.

Summary

In this lab, we learned how to use the instanceof keyword in Java to check if an object is an instance of a specific class or implements a particular interface. We demonstrated its usage by creating a simple program with a base class and subclasses, and then using instanceof to verify the type of an object at runtime.

We further explored how instanceof behaves with subclasses, confirming that an object is considered an instance of its own class as well as any superclasses. Finally, we examined the behavior of instanceof when applied to null objects, understanding that it always returns false in such cases.