Sub topic 13
Getting the Specific Type Back: Casting and instanceof
A variable declared as Animal can hold a Dog. That is useful, but it has a limit. Through an Animal variable, Java only lets you call methods that Animal has. If Dog has an extra method, you need a way to get the Dog back. This chapter shows how to do that safely.
The Problem: Methods Only the Subclass Has
Say Dog has a method called fetch() and Animal does not. This code will not compile:
Animal a = new Dog();
a.fetch(); // compile error: Animal has no fetch()The compiler only knows the declared type, which is Animal. It does not know that the object is a Dog.
Downcasting
Downcasting means converting a reference from a superclass type to a subclass type. You write the subclass name in parentheses:
Animal a = new Dog();
Dog d = (Dog) a; // downcast
d.fetch(); // worksA cast does not change the object. It only changes how your code is allowed to treat it.
There is a risk. If the object is not really a Dog, the cast fails while the program runs:
Animal a = new Cat();
Dog d = (Dog) a; // throws ClassCastExceptionA ClassCastException is an error Java throws when a cast does not match the object's runtime type. The code compiles fine and then crashes.
Checking First with instanceof
The instanceof operator tests whether an object is of a given type. It gives back true or false.
Since Java 16, instanceof can also create a typed variable in the same step. This is called pattern matching for instanceof. If the test passes, the new variable is ready to use, and you never write a cast yourself.
A Worked Example
Save this as Main.java, then compile and run it:
class Animal {
String sound() {
return "...";
}
}
class Dog extends Animal {
@Override
String sound() {
return "Woof";
}
String fetch() {
return "fetches the ball";
}
}
class Cat extends Animal {
@Override
String sound() {
return "Meow";
}
}
public class Main {
static String describe(Animal a) {
if (a instanceof Dog d) {
return "A dog that says " + d.sound() + " and " + d.fetch();
}
return "Some other animal that says " + a.sound();
}
public static void main(String[] args) {
Animal[] animals = { new Dog(), new Cat() };
for (Animal a : animals) {
System.out.println(describe(a));
}
}
}Output:
A dog that says Woof and fetches the ball
Some other animal that says MeowThe Cat never reaches the cast, so nothing crashes.
Older Style
Before Java 16, you tested and cast in two separate steps:
if (a instanceof Dog) {
Dog d = (Dog) a;
System.out.println(d.fetch());
}This is still correct. The newer form is shorter, and you can't forget the check.
Quick Reference
| Action | Syntax | Safe if wrong type? |
|---|---|---|
| Plain downcast | `Dog d = (Dog) a;` | No, throws ClassCastException |
| Type test | `a instanceof Dog` | Yes, returns false |
| Test and bind | `a instanceof Dog d` | Yes, `d` exists only if true |
Exercise
Given Animal a = new Cat();, what happens when the line Dog d = (Dog) a; runs, and how would you rewrite it to be safe?
Show answer
It compiles, but at runtime it throws a ClassCastException because the object is a Cat, not a Dog. A safe version is if (a instanceof Dog d) { ... }, which only uses d when the object really is a Dog.
Exercise
Why does Animal a = new Dog(); a.fetch(); fail to compile even though the object is a Dog?
Show answer
The compiler checks method calls against the declared type, Animal, and Animal has no fetch() method. You must downcast to Dog before calling fetch().