9.3 Reference Casting (Upcasting, Downcasting) & instanceof

Key Takeaways

  • Upcasting from a subclass to a superclass or implemented interface is always safe and implicit, requiring no cast operator

  • A narrowing cast such as (Dog) pet leaves the referenced object unchanged. At run time it accepts null or a compatible object and otherwise throws ClassCastException.

  • The compiler rejects casts between unrelated classes (such as String and Integer), as well as casts between a final class and an unimplemented interface

  • A non-final class can often be cast to an interface it does not implement, because a subtype could implement it. Incompatible generic parameterizations can still make a cast illegal.

  • instanceof returns false for a null reference. In Java 8 the test needs a legal reference cast relationship and a reifiable target, such as List<?>.

Last updated: November 2026

Reference Casting (Upcasting, Downcasting) & instanceof

Casting a reference variable changes only the compile-time reference type used to view an object; it never transforms or copies the actual object on the heap. The compiler checks whether the conversion is permitted. A checked narrowing cast then tests the non-null object at runtime. A widening reference conversion needs no such runtime test.

Implicit Upcasting vs. Explicit Downcasting

Moving up an inheritance hierarchy—from a subtype to a supertype—is called upcasting. Because every Dog is an Animal and every Animal is an Object, an upcast can never fail and requires no explicit cast syntax:

Dog d = new Dog();
Animal a = d;       // Implicit upcast: Dog -> Animal
Object o = a;       // Implicit upcast: Animal -> Object
Animal a2 = (Animal) d; // Explicit upcast: legal, though redundant

Moving down the hierarchy—from a general reference type to a more specific subtype—is called downcasting. Because Animal a might refer to a Cat rather than a Dog, the compiler demands an explicit cast operator (Dog) to acknowledge the risk:

Animal a = new Dog();
Dog d = (Dog) a;    // Compiles and succeeds at runtime; a actually refers to a Dog
d.bark();           // Now bark() is visible at compile time

Note

Casting null to any reference type—such as Dog d = (Dog) null;—compiles and succeeds at runtime without throwing ClassCastException. The variable d simply receives null.


Compile-Time Cast Rejection vs. Compiler Permission

On the Java SE 8 Associate exam, you must predict whether a cast causes a compile-time error or compiles cleanly and throws ClassCastException at runtime. The compiler applies three distinct rules depending on whether classes and interfaces are involved:

Cast ScenarioExampleCompiler ResultRuntime Result
Upcast to supertypeObject o = (Object) "hi";CompilesSucceeds
Downcast along class hierarchyAnimal a = new Cat(); Dog d = (Dog) a;CompilesThrows ClassCastException
Unrelated classes (no extends path)String s = (String) new Integer(1);Compile-time errorNever runs
Non-final class to unimplemented interfaceObject o = new Object(); Runnable r = (Runnable) o;CompilesThrows ClassCastException
Interface to unimplemented non-final classRunnable r = new Thread(); Animal a = (Animal) r;CompilesThrows ClassCastException
final class to unimplemented interfaceRunnable r = (Runnable) "text";Compile-time errorNever runs

Why Interfaces Follow a Different Compiler Rule

Between two classes, Java permits single inheritance only. If Dog and Cat are sibling classes (Dog extends Animal, Cat extends Animal), no single object can ever be both a Dog and a Cat. The compiler knows the cast (Cat) dog is mathematically impossible and rejects it immediately:

Dog dog = new Dog();
// Cat cat = (Cat) dog;           // DOES NOT COMPILE: inconvertible types
// String s = (String) new Integer(1); // DOES NOT COMPILE: inconvertible types

Between a non-final class and an interface, however, a subclass could exist at runtime that extends the class and implements the interface! For example, even though Animal does not implement Runnable, someone could write class RunningDog extends Dog implements Runnable. The compiler allows this cast. Where generic supertypes prove two parameterizations incompatible, a cast can still fail at compile time.

Animal a = new Animal();
Runnable r = (Runnable) a; // Compiles! A subclass of Animal might implement Runnable
// At runtime: throws ClassCastException because new Animal() is not Runnable

Now watch what changes when the class is final:

String text = "Java 8";
CharSequence cs = (CharSequence) text; // Compiles & succeeds: String implements CharSequence
// Runnable r = (Runnable) text;       // DOES NOT COMPILE: String is final and cannot have subclasses!

Because String is final, it can never have a subclass that implements Runnable. The compiler proves that no object referenced by text could ever be a Runnable, so it rejects (Runnable) text at compile time. The reverse is equally true: if Runnable r is cast to (String) r, compilation fails because String is final and does not implement Runnable.

Operator Precedence Trap in Cast Expressions

Member access (.) has higher precedence than the cast operator (Type). Forgetting outer parentheses causes a compile-time error when chaining a method call onto a cast:

Animal a = new Dog();
// (Dog) a.bark();     // DOES NOT COMPILE: parsed as (Dog) (a.bark()), and Animal lacks bark()
((Dog) a).bark();      // Compiles: cast completes first, then bark() is called on Dog

Runtime ClassCastException & the instanceof Guard

When a syntactically legal downcast encounters an incompatible runtime object, the JVM throws java.lang.ClassCastException:

Animal a = new Cat();
Dog d = (Dog) a; // Compiles cleanly, throws ClassCastException at runtime

To prevent ClassCastException, guard downcasts with the instanceof operator (reference instanceof TargetType). At runtime, instanceof returns true if the object is an instance of TargetType or any subtype (class or interface) of TargetType:

public static void handleAnimal(Animal a) {
    if (a instanceof Dog) {
        Dog d = (Dog) a;
        d.bark();
    } else if (a instanceof Cat) {
        System.out.println("Purr");
    }
}

Three Crucial instanceof Rules for the Exam

  1. null instanceof AnyType is ALWAYS false: Checking null instanceof Object or null instanceof String never throws NullPointerException—it safely evaluates to false.
  2. Compile-time compatibility: Java 8 rejects an instanceof test when the same reference cast is illegal. The test also has its own restriction on target types:
    • dog instanceof String (unrelated classes) fails compilation.
    • "text" instanceof Runnable (final class vs. unimplemented interface) fails compilation.
    • dog instanceof Runnable (non-final class vs. interface) compiles cleanly and returns false at runtime (unless dog holds a subclass implementing Runnable).
  3. Right-hand side must be a reifiable reference type: Primitives (5 instanceof int) fail compilation.
Animal mystery = null;
System.out.println(mystery instanceof Animal);   // false (no NPE!)
System.out.println(mystery instanceof Runnable); // false (compiles: Animal is non-final)
// System.out.println("abc" instanceof Integer); // DOES NOT COMPILE: unrelated classes
// System.out.println("abc" instanceof Runnable);// DOES NOT COMPILE: String is final

Tip

A legal cast does not guarantee a legal test. From an Object expression, a cast to List<String> can compile with an unchecked warning, but instanceof List<String> fails in Java 8. Use instanceof List<?> to test for a list without claiming an element type.

Test Your Knowledge

Assume Animal and its non-final subclass Dog are in scope, and Serializable means java.io.Serializable. Which statement fails to compile in Java SE 8?

A

Object o = new Object(); Runnable r = (Runnable) o;

B

Animal a = new Dog(); boolean check = a instanceof Serializable;

C

String s = "hello"; Runnable r = (Runnable) s;

D

Runnable r = null; Dog d = (Dog) r;

Test Your Knowledge

What is the result of compiling and running the following code?

Object item = null;
if (item instanceof String) {
    System.out.println("Text");
} else {
    String s = (String) item;
    System.out.println(s);
}
A

Throws NullPointerException on the instanceof check

B

Prints null

C

Throws ClassCastException on (String) item

D

Fails to compile because Object cannot be cast to String

Test Your Knowledge

Suppose class Bird {} and class Sparrow extends Bird {}, and neither implements AutoCloseable. Which line causes a compile-time error?

A

Bird b = new Sparrow(); System.out.println(b instanceof Integer);

B

Bird b = new Bird(); System.out.println(b instanceof AutoCloseable);

C

Bird b = new Sparrow(); ((Sparrow) b).toString();

D

AutoCloseable ac = (AutoCloseable) new Bird();

Sections you finish are checked off in the contents.