Downcasting and ClassCastException
32 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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); }}Dog fetches the ball Dog fetches the ball true
What this code does
(Dog) aturns theAnimalreference into aDogreference, sofetch()can be called.- No new object is made:
a == distrue.((Dog) a).fetch()does the cast and the call in one line.
Example 2 · A realistic downcast: the topper's scholarship
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()); }}Priya gets Rs. 7000
What this code does
classTopper()returns the parent typeStudent, sos.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.
((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
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(); }}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
Animalcould be a dog. At run time the JVM sees aCatand throwsClassCastException. ClassCastExceptionis 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.
Example 4 · Mistake: casting between siblings
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(); }}SiblingCastDemo.java:22: error: incompatible types: Cat cannot be converted to Dog
Dog d = (Dog) c;
^
1 errorWhat this code does
- A
Catvariable can never hold a dog, so javac refuses the cast before the program runs. - Compare with Example 3: through an
Animalvariable 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.
(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
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); }}Puppy runs after the ball and forgets it Puppy null
What this code does
- A
PuppyIS-ADog, so the cast toDogworks. It changes only the view: the overriddenfetch()ofPuppystill runs. - Casting
nullgivesnullwith no exception; only calling a method onnobodywould throw aNullPointerException.
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.
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