The instanceof Operator
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 31 of 87.
The previous lesson showed that downcasting can fail with a ClassCastException if the object isn't actually the type you're casting to. The instanceof operator solves this by letting you check an object's type before casting.
The syntax is straightforward: object instanceof ClassName returns true if the object is an instance of that class (or any of its subclasses):
Animal animal = new Dog();
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
dog.bark(); // Safe to call Dog-specific methods
}This check prevents runtime errors by ensuring the cast will succeed. The operator also returns true for parent types in the hierarchy:
Dog dog = new Dog();
System.out.println(dog instanceof Dog); // true
System.out.println(dog instanceof Animal); // true
System.out.println(dog instanceof Object); // trueSince Java 16, you can combine the check and cast in one step using pattern matching:
if (animal instanceof Dog dog) {
dog.bark(); // 'dog' is already cast and ready to use
}This cleaner syntax eliminates the separate cast line. Note that instanceof returns false when tested against null, so you don't need a separate null check.
Challenge
EasyLet's build a vehicle inspection system that uses the instanceof operator to safely identify and handle different vehicle types. You'll create a hierarchy of vehicles and write code that checks each vehicle's actual type before accessing its specialized features.
You'll organize your code across four files:
Vehicle.java: Create the base class that all vehicles share. Every vehicle has amodelfield (String). Include a constructor to initialize it, a getter methodgetModel(), and a methodinspect()that prints:Inspecting vehicle: [model]Car.java: Create a class that extends Vehicle. Cars have an additionalnumDoorsfield (int). Usesuperfor the parent initialization. Add a methodcheckDoors()that prints:[model] has [numDoors] doorsMotorcycle.java: Create another class that extends Vehicle. Motorcycles have ahasSidecarfield (boolean). Add a methodcheckSidecar()that prints either[model] has a sidecaror[model] has no sidecardepending on the boolean value.Main.java: Here's whereinstanceofbecomes essential! You'll receive four inputs: a car model, number of doors, a motorcycle model, and whether it has a sidecar (true/false).Create an array of
Vehiclereferences containing a Car and a Motorcycle. Then loop through the array and for each vehicle:- Call the base
inspect()method - Use
instanceofto check if it's a Car - if so, safely downcast and callcheckDoors() - Use
instanceofto check if it's a Motorcycle - if so, safely downcast and callcheckSidecar()
- Call the base
You will receive four inputs: the car model (String), number of doors (int), motorcycle model (String), and has sidecar (boolean).
Your output should show four lines - for each vehicle, you'll see its inspection message followed by its type-specific check. The instanceof operator ensures you only call Car methods on actual Cars and Motorcycle methods on actual Motorcycles, preventing any ClassCastException!
Cheat sheet
The instanceof operator checks if an object is an instance of a specific class before casting:
Animal animal = new Dog();
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
dog.bark(); // Safe to call Dog-specific methods
}The operator returns true for the object's class and all parent classes in the hierarchy:
Dog dog = new Dog();
System.out.println(dog instanceof Dog); // true
System.out.println(dog instanceof Animal); // true
System.out.println(dog instanceof Object); // trueSince Java 16, pattern matching combines the check and cast in one step:
if (animal instanceof Dog dog) {
dog.bark(); // 'dog' is already cast and ready to use
}The instanceof operator returns false when tested against null, eliminating the need for separate null checks.
Try it yourself
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read inputs
String carModel = scanner.nextLine();
int numDoors = Integer.parseInt(scanner.nextLine());
String motorcycleModel = scanner.nextLine();
boolean hasSidecar = Boolean.parseBoolean(scanner.nextLine());
// TODO: Create a Car object with carModel and numDoors
// TODO: Create a Motorcycle object with motorcycleModel and hasSidecar
// TODO: Create an array of Vehicle references containing the Car and Motorcycle
// TODO: Loop through the array and for each vehicle:
// 1. Call the inspect() method
// 2. Use instanceof to check if it's a Car, then downcast and call checkDoors()
// 3. Use instanceof to check if it's a Motorcycle, then downcast and call checkSidecar()
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System