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.
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.
Open the
HelloJava.javafile in the WebIDE editor if it's not already open.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
Animaland two subclassesDogandCat. - In the
mainmethod, we create anAnimalvariablemyAnimaland assign aDogobject to it. - We then use the
instanceofoperator to check ifmyAnimalis an instance ofDog,Cat, andAnimal.
- We define a base class
Save the file (Ctrl+S or Cmd+S).
Compile the program using the
javaccommand in the Terminal:javac HelloJava.javaRun the compiled program using the
javacommand:java HelloJavaYou should see output indicating which
instanceofchecks returned true.myAnimal is an instance of Dog myAnimal is an instance of AnimalAs you can see,
myAnimalis an instance ofDog(because we created aDogobject) and also an instance ofAnimal(becauseDogis a subclass ofAnimal). It is not an instance ofCat.
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.
Open the
HelloJava.javafile in the WebIDE editor.Add a new class called
Carto the file. You can add this class definition before or after theAnimal,Dog, andCatclasses, but outside of theHelloJavaclass.class Car { public void drive() { System.out.println("Driving a car"); } }Now, let's modify the
mainmethod within theHelloJavaclass to create aCarobject and test theinstanceofoperator. Update themainmethod 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
CarobjectmyCarand includedinstanceofchecks for it againstCarandAnimal.Save the file (Ctrl+S or Cmd+S).
Compile the modified program:
javac HelloJava.javaRun the program:
java HelloJavaObserve the output. You should see the results from the previous step, followed by the results of the new checks for the
Carobject.myAnimal is an instance of Dog myAnimal is an instance of Animal --- Testing Car object --- myCar is an instance of CarThis output confirms that
myCaris an instance ofCar, but it is not an instance ofAnimalbecauseCardoes not inherit fromAnimal. Theinstanceofoperator 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.
Open the
HelloJava.javafile in the WebIDE editor.Modify the
mainmethod within theHelloJavaclass to include anullAnimalreference and test it. Update themainmethod 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
AnimalvariablenullAnimaland initialized it tonull. We then performinstanceofchecks against it.Save the file (Ctrl+S or Cmd+S).
Compile the program:
javac HelloJava.javaRun the program:
java HelloJavaObserve 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
ifblocks fornullAnimalare not printed. This is becausenullAnimal instanceof AnimalandnullAnimal instanceof Dogboth evaluate tofalse. This demonstrates that theinstanceofoperator correctly handlesnullreferences by returningfalse.
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.



