Sub topic 13
Getting the Specific Type Back: Casting and instanceof
In earlier chapters you stored a Dog in a variable of type Animal. That is called upcasting. Upcasting means treating an object as one of its superclasses. Java does it for you automatically, and it is always safe.
Upcasting has a cost, though. Once a Dog sits in an Animal variable, the compiler only lets you call methods that Animal has. If Dog has an extra method, such as fetch(), you cannot reach it through that variable.
This chapter shows how to get the specific type back. You will learn about downcasting, the instanceof operator, and the newer pattern matching for instanceof. You will also learn when not to use them.
Why the Declared Type Limits You
The declared type is the type written next to the variable name. The runtime type is the class of the object the variable actually refers to. The compiler only knows the declared type. It decides which method calls are allowed by looking at that type.
class Animal {
String sound() {
return "...";
}
}
class Dog extends Animal {
@Override
String sound() {
return "Woof";
}
String fetch() {
return "Dog fetches the ball";
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
System.out.println(a.sound()); // Woof
// System.out.println(a.fetch()); // compile error: cannot find symbol
}
}The call a.sound() works, because Animal has sound(), and overriding makes the Dog version run. The call a.fetch() does not compile. The object really is a Dog, but the compiler only sees Animal, and Animal has no fetch() method.
Downcasting
A downcast tells the compiler: "I know this Animal is really a Dog. Treat it as one." You write the target type in parentheses before the value.
Animal a = new Dog();
Dog d = (Dog) a;
System.out.println(d.fetch()); // Dog fetches the ballA cast does not change the object. The object was a Dog all along. The cast only changes the type the compiler uses for this one expression.
What happens when the cast is wrong
The compiler trusts you, but the JVM checks the cast while the program runs. The JVM (Java Virtual Machine) is the program that runs your compiled Java code. If the object is not of the target type, the JVM throws a ClassCastException. An exception is an error that stops normal execution unless your code catches it.
Here is a complete program that shows both a good cast and a bad cast:
class Animal {
String sound() {
return "...";
}
}
class Dog extends Animal {
@Override
String sound() {
return "Woof";
}
String fetch() {
return "Dog fetches the ball";
}
}
class Cat extends Animal {
@Override
String sound() {
return "Meow";
}
String climb() {
return "Cat climbs the tree";
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
Dog d = (Dog) a; // fine: the object is a Dog
System.out.println(d.fetch());
Animal b = new Cat();
try {
Dog wrong = (Dog) b; // compiles, but fails at runtime
System.out.println(wrong.fetch());
} catch (ClassCastException e) {
System.out.println("Cast failed: " + e.getMessage());
}
}
}The output starts with Dog fetches the ball. Then it prints Cast failed: and a message saying that Cat cannot be cast to Dog.
Casts the compiler rejects
The compiler does stop casts that can never succeed. A String can never be an Animal, because the two classes are unrelated. So this line will not compile:
Animal a = new Dog();
// String s = (String) a; // compile error: incompatible typesThe compiler allows a cast only between types that are related through inheritance. Between those types, it is up to you to be right.
Checking First with instanceof
The instanceof operator asks a question at runtime: "Is this object an instance of this type?" It returns true or false. An object is an instance of its own class and of every superclass and interface above it.
Animal a = new Dog();
System.out.println(a instanceof Dog); // true
System.out.println(a instanceof Animal); // true
System.out.println(a instanceof Cat); // false
Animal nothing = null;
System.out.println(nothing instanceof Animal); // falseNote the last line. null is not an instance of anything, so instanceof returns false. This means a passing instanceof check also tells you the value is not null.
The classic way to cast safely is to check, then cast:
if (a instanceof Dog) {
Dog d = (Dog) a;
System.out.println(d.fetch());
}This works, but you have to write Dog three times. It is also easy to check one type and then cast to another by mistake.
Pattern Matching for instanceof
Java 16 added pattern matching for instanceof. A pattern is a type plus a variable name. If the test passes, Java casts the value for you and puts it in the new variable. This variable is called a binding variable.
static String describe(Animal a) {
if (a instanceof Dog d) {
return d.fetch();
} else if (a instanceof Cat c) {
return c.climb();
}
return "Just an animal: " + a.sound();
}Here d exists only where the test is known to be true. You cannot misuse it, because it is never created for a failed test.
The diagram below shows the decision Java makes for a instanceof Dog d.
Where the binding variable can be used
Java tracks where the test must have been true. Here are some useful cases:
- With
&&, you can use the variable on the right side:if (a instanceof Dog d && d.fetch().length() > 0). The right side only runs if the left side was true. - With a negated test and an early return, the variable stays in scope after the
if:
static String fetchOrComplain(Animal a) {
if (!(a instanceof Dog d)) {
return "Not a dog";
}
return d.fetch(); // d is usable here
}- With
||, you cannot use the variable on the right side. If the left side is false,dwas never set.
Check the more specific type first
Suppose GuideDog extends Dog. A guide dog is also a dog. If you test instanceof Dog before instanceof GuideDog, the Dog branch catches every guide dog. The GuideDog branch then never runs. Always test subclasses before their superclasses.
Summary of the Tools
| Tool | When it is checked | What happens if the type is wrong |
|---|---|---|
| Upcast, e.g. `Animal a = new Dog();` | Compile time | Cannot be wrong, always safe |
| Downcast, e.g. `(Dog) a` | Runtime, by the JVM | Throws ClassCastException |
| Cast between unrelated types | Compile time | Compile error |
| `a instanceof Dog` | Runtime | Returns false |
| `a instanceof Dog d` (Java 16+) | Runtime | Returns false, `d` is not created |
When Not to Cast
Casting is sometimes needed. Common cases are writing equals methods and working with old code that returns Object. But a long chain of instanceof checks often means the design is missing an overridden method.
Look at describe above. Each time you add a new animal, you must edit that method. If you forget, the new animal falls through to the default case with no warning. If you add an overridden trick() method to Animal instead, each class supplies its own behavior, and dynamic dispatch picks the right one.
A later chapter shows sealed types. With sealed types, the compiler knows every possible subclass and can check that your type tests cover all of them.
Exercise
Given Animal x = new Cat();, what happens with each line? (1) Cat c = (Cat) x; (2) Dog d = (Dog) x; (3) String s = (String) x;
Show answer
(1) Compiles and runs fine, because the object really is a Cat. (2) Compiles, because Dog and Animal are related, but throws ClassCastException at runtime, because the object is a Cat and not a Dog. (3) Does not compile, because String and Animal are unrelated types, so the cast can never succeed.
Exercise
What does this print? Animal a = null; System.out.println(a instanceof Animal); Why is this useful?
Show answer
It prints false. instanceof always returns false for null. This means that if a pattern test such as a instanceof Dog d passes, you know d is not null and can call methods on it safely.
Exercise
Rewrite this code to use pattern matching for instanceof: if (a instanceof Cat) { Cat c = (Cat) a; System.out.println(c.climb()); }
Show answer
if (a instanceof Cat c) { System.out.println(c.climb()); } The test and the cast happen in one step. The variable c exists only inside the block where the test was true.
Exercise
Class GuideDog extends Dog. A method checks if (a instanceof Dog d) first and else if (a instanceof GuideDog g) second. A GuideDog is passed in. Which branch runs, and how do you fix it?
Show answer
The Dog branch runs, because a GuideDog is also a Dog. The GuideDog branch can never run. Fix it by testing for GuideDog first, then Dog.