How to Check If an Object Is of a Specific Type in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if an object is of a specific type in Java using the instanceof operator. You will start by understanding the basic usage of instanceof with different classes, including inheritance.

You will then test the instanceof operator with various class types and explore how it behaves with subclasses and superclasses. Finally, you will learn how to handle null objects when using instanceof to avoid potential errors.


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/inheritance("Inheritance") subgraph Lab Skills java/if_else -.-> lab-560012{{"How to Check If an Object Is of a Specific Type in Java"}} java/classes_objects -.-> lab-560012{{"How to Check If an Object Is of a Specific Type in Java"}} java/inheritance -.-> lab-560012{{"How to Check If an Object Is of a Specific Type in Java"}} end

Use instanceof Operator

In this step, you will learn about the instanceof operator in Java. The instanceof operator 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 the instanceof operator works.

  1. Open the HelloJava.java file in the WebIDE editor if it's not already open.

  2. Replace the entire contents of the file with the following code:

    class Animal {
        public void makeSound() {
            System.out.println("Generic animal sound");
        }
    }
    
    class Dog extends Animal {
        public void makeSound() {
            System.out.println("Woof!");
        }
    }
    
    class Cat extends Animal {
        public void makeSound() {
            System.out.println("Meow!");
        }
    }
    
    public class HelloJava {
        public static void main(String[] args) {
            Animal myAnimal = new Dog();
    
            if (myAnimal instanceof Dog) {
                System.out.println("myAnimal is an instance of Dog");
            }
    
            if (myAnimal instanceof Cat) {
                System.out.println("myAnimal is an instance of Cat");
            }
    
            if (myAnimal instanceof Animal) {
                System.out.println("myAnimal is 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.
    • We then use the instanceof operator to check if myAnimal is an instance of Dog, Cat, and Animal.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the program using the javac command in the Terminal:

    javac HelloJava.java
  5. Run the compiled program using the java command:

    java HelloJava

    You should see output indicating which instanceof checks returned true.

    myAnimal is an instance of Dog
    myAnimal is an instance of Animal

    As you can see, myAnimal is an instance of Dog (because we created a Dog object) and also an instance of Animal (because Dog is a subclass of Animal). It is not an instance of Cat.

Test with Different Classes

In the previous step, you saw how instanceof works with a subclass and its superclass. Now, let's explore how it behaves when testing against different, unrelated classes.

We will modify our existing HelloJava.java file to include another class and test the instanceof operator with objects of different types.

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

  2. Add a new class called Car to the file. You can add this class definition before or after the Animal, Dog, and Cat classes, but outside of the HelloJava class.

    class Car {
        public void drive() {
            System.out.println("Driving a car");
        }
    }
  3. Now, let's modify the main method within the HelloJava class to create a Car object and test the instanceof operator. Update the main method to look like this:

    public class HelloJava {
        public static void main(String[] args) {
            Animal myAnimal = new Dog();
            Car myCar = new Car();
    
            if (myAnimal instanceof Dog) {
                System.out.println("myAnimal is an instance of Dog");
            }
    
            if (myAnimal instanceof Cat) {
                System.out.println("myAnimal is an instance of Cat");
            }
    
            if (myAnimal instanceof Animal) {
                System.out.println("myAnimal is an instance of Animal");
            }
    
            System.out.println("--- Testing Car object ---");
    
            if (myCar instanceof Car) {
                System.out.println("myCar is an instance of Car");
            }
    
            if (myCar instanceof Animal) {
                System.out.println("myCar is an instance of Animal");
            }
        }
    }

    We've added a new Car object myCar and included instanceof checks for it against Car and Animal.

  4. Save the file (Ctrl+S or Cmd+S).

  5. Compile the modified program:

    javac HelloJava.java
  6. Run the program:

    java HelloJava

    Observe the output. You should see the results from the previous step, followed by the results of the new checks for the Car object.

    myAnimal is an instance of Dog
    myAnimal is an instance of Animal
    --- Testing Car object ---
    myCar is an instance of Car

    This output confirms that myCar is an instance of Car, but it is not an instance of Animal because Car does not inherit from Animal. The instanceof operator correctly identifies the type relationship (or lack thereof) between objects and classes.

Handle Null Objects

In this final step, we will explore how the instanceof operator behaves when dealing with null objects. Understanding this is important to avoid unexpected errors in your programs.

A null reference in Java means that a variable does not refer to any object. When you use the instanceof operator with a null reference, it will always return false. This is a built-in safety feature of the operator.

Let's modify our HelloJava.java file one last time to include a null object and test the instanceof operator.

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

  2. Modify the main method within the HelloJava class to include a null Animal reference and test it. Update the main method to look like this:

    class Animal {
        public void makeSound() {
            System.out.println("Generic animal sound");
        }
    }
    
    class Dog extends Animal {
        public void makeSound() {
            System.out.println("Woof!");
        }
    }
    
    class Cat extends Animal {
        public void makeSound() {
            System.out.println("Meow!");
        }
    }
    
    class Car {
        public void drive() {
            System.out.println("Driving a car");
        }
    }
    
    public class HelloJava {
        public static void main(String[] args) {
            Animal myAnimal = new Dog();
            Car myCar = new Car();
            Animal nullAnimal = null; // Declare a null Animal reference
    
            if (myAnimal instanceof Dog) {
                System.out.println("myAnimal is an instance of Dog");
            }
    
            if (myAnimal instanceof Cat) {
                System.out.println("myAnimal is an instance of Cat");
            }
    
            if (myAnimal instanceof Animal) {
                System.out.println("myAnimal is an instance of Animal");
            }
    
            System.out.println("--- Testing Car object ---");
    
            if (myCar instanceof Car) {
                System.out.println("myCar is an instance of Car");
            }
    
            if (myCar instanceof Animal) {
                System.out.println("myCar is an instance of Animal");
            }
    
            System.out.println("--- Testing null object ---");
    
            if (nullAnimal instanceof Animal) {
                System.out.println("nullAnimal is an instance of Animal");
            }
    
            if (nullAnimal instanceof Dog) {
                System.out.println("nullAnimal is an instance of Dog");
            }
        }
    }

    We've added a new Animal variable nullAnimal and initialized it to null. We then perform instanceof checks against it.

  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the program:

    javac HelloJava.java
  5. Run the program:

    java HelloJava

    Observe the output. You should see the results from the previous steps, followed by the results of the checks for the nullAnimal.

    myAnimal is an instance of Dog
    myAnimal is an instance of Animal
    --- Testing Car object ---
    myCar is an instance of Car
    --- Testing null object ---

    Notice that the lines inside the if blocks for nullAnimal are not printed. This is because nullAnimal instanceof Animal and nullAnimal instanceof Dog both evaluate to false. This demonstrates that the instanceof operator correctly handles null references by returning false.

Understanding how instanceof works with null is crucial for writing robust Java code that avoids NullPointerException errors.

Summary

In this lab, you learned how to check if an object is of a specific type in Java using the instanceof operator. You practiced using instanceof with different classes, including a base class and its subclasses, to determine the runtime type of an object. You also explored how instanceof behaves when checking against the object's actual class, its superclass, and unrelated classes.