Skip to lesson

Downcasting and ClassCastException

A parent-type variable hides the child's own methods. Downcasting gets them back with a cast, Dog d = (Dog) a;. It is a promise to the compiler, and the JVM checks that promise while the program runs.

Getting the child type back

Downcasting is converting a parent-type reference into a child-type reference with an explicit cast, like Dog d = (Dog) a;. It compiles only when the cast could work, and the JVM checks the real object while the program runs.

Animal a = new Dog(); hides fetch(), because Animal has no such method. You know the object is a dog, so you write the child type in brackets: Dog d = (Dog) a;. Now d.fetch() compiles.

Example 1 · A downcast that works

DowncastDemo.javaJava
class Animal {    void sound() {        System.out.println("Some sound");    }}
class Dog extends Animal {    void fetch() {        System.out.println("Dog fetches the ball");    }}
class Cat extends Animal {    void climb() {        System.out.println("Cat climbs the wall");    }}
public class DowncastDemo {    public static void main(String[] args) {        Animal a = new Dog();        Dog d = (Dog) a;        d.fetch();        ((Dog) a).fetch();        System.out.println(a == d);    }}
Output
Dog fetches the ball
Dog fetches the ball
true

What this code does

  • (Dog) a turns the Animal reference into a Dog reference, so fetch() can be called.
  • No new object is made: a == d is true. ((Dog) a).fetch() does the cast and the call in one line.

Example 2 · A realistic downcast: the topper's scholarship

ScholarshipDemo.javaJava
class Student {    String name;    int marks;
    Student(String name, int marks) {        this.name = name;        this.marks = marks;    }}
class Topper extends Student {    Topper(String name, int marks) {        super(name, marks);    }
    int scholarship() {        return (marks - 90) * 1000;    }}
public class ScholarshipDemo {    static Student classTopper() {        return new Topper("Priya", 97);    }
    public static void main(String[] args) {        Student s = classTopper();        Topper t = (Topper) s;        System.out.println(t.name + " gets Rs. " + t.scholarship());    }}
Output
Priya gets Rs. 7000

What this code does

  • classTopper() returns the parent type Student, so s.scholarship() would not compile.
  • The caller knows this method always returns a Topper, so the cast is safe here.

The cast creates nothing: d and a point to the same dog, so a == d is true. Without the cast, Dog d = a; is the incompatible types error from Reference type vs object type (opens in a new tab): going down is never automatic.

To cast and call in one line, wrap the cast in brackets: ((Dog) a).fetch();. Without them the call runs first, so (Dog) a.fetch() tries to cast the result of a.fetch().

ClassCastException: the cast that fails at run time

ClassCastException is the unchecked exception the JVM throws when a cast names a type the object is not, like (Dog) a when a points to a Cat. Its message names the object's class first, then the target class.

javac allows (Dog) a because an Animal variable could hold a dog. Only at run time does the JVM see the real object. If it is a Cat, the cast fails.

Example 3 · Mistake: the object is not a Dog

WrongCastDemo.javaJava
class Animal {    void sound() {        System.out.println("Some sound");    }}
class Dog extends Animal {    void fetch() {        System.out.println("Dog fetches the ball");    }}
class Cat extends Animal {    void climb() {        System.out.println("Cat climbs the wall");    }}
public class WrongCastDemo {    public static void main(String[] args) {        Animal a = new Cat();        System.out.println("Before the cast");        Dog d = (Dog) a;        System.out.println("After the cast");        d.fetch();    }}
Sample output
Before the cast
Exception in thread "main" java.lang.ClassCastException: class Cat cannot be cast to class Dog (Cat and Dog are in unnamed module of loader 'app')
	at WrongCastDemo.main(WrongCastDemo.java:23)

What this code does

  • The cast compiles, because an Animal could be a dog. At run time the JVM sees a Cat and throws ClassCastException.
  • ClassCastException is unchecked: javac never asks you to catch it. It signals a wrong assumption in the code, not bad input.

Read the message from the left: class Cat cannot be cast to class Dog names the object type, then the target. The line at WrongCastDemo.main(WrongCastDemo.java:23) points at the failing cast, and "After the cast" never prints.

Casts the compiler refuses

Some casts can never work. A Cat variable can only hold a cat (or a cat's child), so (Dog) myCat is refused before the program runs. Between two classes, one must be a parent or child of the other.

Three casts to Dog. With Animal a = new Dog(); the cast (Dog) a works and gives a Dog reference to the same object. With Animal a = new Cat(); (Dog) a compiles but throws ClassCastException at run time. With Cat c = new Cat(); (Dog) c is refused by javac: incompatible types.

Example 4 · Mistake: casting between siblings

SiblingCastDemo.javaJava
class Animal {    void sound() {        System.out.println("Some sound");    }}
class Dog extends Animal {    void fetch() {        System.out.println("Dog fetches the ball");    }}
class Cat extends Animal {    void climb() {        System.out.println("Cat climbs the wall");    }}
public class SiblingCastDemo {    public static void main(String[] args) {        Cat c = new Cat();        Dog d = (Dog) c;        d.fetch();    }}
Sample compiler output
SiblingCastDemo.java:22: error: incompatible types: Cat cannot be converted to Dog
        Dog d = (Dog) c;
                      ^
1 error

What this code does

  • A Cat variable can never hold a dog, so javac refuses the cast before the program runs.
  • Compare with Example 3: through an Animal variable the same mistake is found only at run time.

So a cast has three possible results, as in the picture: refused by javac, ClassCastException at run time, or it works. Unrelated classes such as String and Dog are refused too. Only the real object decides between the last two.

Interfaces are looser: (Payable) someAnimal compiles when Animal is not final, because some child class might implement Payable. The JVM still checks it at run time.

Cast to what the object is

A cast works when the object IS-A the target type. A Puppy object can be cast to Puppy, Dog, Animal or Object. Casting null always works and gives null.

Example 5 · Casting to a middle class, and casting null

MiddleCastDemo.javaJava
class Animal {    void sound() {        System.out.println("Some sound");    }}
class Dog extends Animal {    void fetch() {        System.out.println("Dog fetches the ball");    }}
class Puppy extends Dog {    @Override    void fetch() {        System.out.println("Puppy runs after the ball and forgets it");    }}
public class MiddleCastDemo {    public static void main(String[] args) {        Animal a = new Puppy();        Dog d = (Dog) a;        d.fetch();        System.out.println(d.getClass().getSimpleName());
        Animal none = null;        Dog nobody = (Dog) none;        System.out.println(nobody);    }}
Output
Puppy runs after the ball and forgets it
Puppy
null

What this code does

  • A Puppy IS-A Dog, so the cast to Dog works. It changes only the view: the overridden fetch() of Puppy still runs.
  • Casting null gives null with no exception; only calling a method on nobody would throw a NullPointerException.

A cast changes only the view, so it changes what you may call, never which overridden version runs. Every downcast is still a risk; instanceof and pattern matching (opens in a new tab) shows how to check first, and often an overridden method removes the cast altogether.

Fix the error

Fix the cast

Read the error, then pick the line that fixes it.

Round 1 of 3

The dog is at index 1. Make this fetch the ball.

Animal[] pets = { new Cat(), new Dog() };
Dog d = (Dog) pets[0];
d.fetch();

Error

Exception in thread "main" java.lang.ClassCastException: class Cat cannot be cast to class Dog (Cat and Dog are in unnamed module of loader 'app')

Next step

Check your understanding

12 quick questions