Course contentsShow
← Java
Lesson 451 of 2,87011. Polymorphism and Dynamic DispatchFree lesson

Common instanceof Use Cases Before Pattern Matching

Explore typical pre-Java 16 patterns: instanceof check followed by explicit cast in conditional branches.

Common instanceof Use Cases Before Pattern Matching

What you'll learn: You'll see the typical pre-Java 16 pattern of checking an object's type with instanceof, then explicitly casting it to access subclass-specific features.


Before pattern matching arrived in Java 16, the instanceof operator was commonly paired with an explicit cast. This two-step dance appeared everywhere: check the type, then cast if true.

The Classic Pattern

The most common use case looked like this:

if (animal instanceof Dog) {
    Dog dog = (Dog) animal;  // explicit cast
    dog.bark();  // now we can call Dog-specific methods
}

You'd first verify the object is actually a Dog, then perform a manual cast to a Dog variable so you could access bark() or other subclass-specific members.

Multiple Type Checks

When handling various subclasses, you'd chain if-else blocks:

if (shape instanceof Circle) {
    Circle c = (Circle) shape;
    System.out.println("Radius: " + c.getRadius());
} else if (shape instanceof Rectangle) {
    Rectangle r = (Rectangle) shape;
    System.out.println("Width: " + r.getWidth());
}

Each branch required its own instanceof check followed by a cast.

Why This Pattern Existed

Without the cast, you couldn't access subclass-specific methods—the compiler only knew about the superclass reference type. The instanceof check prevented ClassCastException at runtime, making the cast safe.

This pattern was verbose but necessary: three lines (check, cast, use) just to access specialized behavior.

Key Takeaway:
Before pattern matching, the standard idiom was instanceof check → explicit cast → use subclass features, resulting in repetitive but safe code.