Skip to content

Java OOP

0/36 lessons · 0% complete

— XP

Java OOP · Module 8

Upcasting, downcasting, instanceof

Widening the view safely — and narrowing it carefully

22m55 XP
→→→

What you'll be able to do

  • Explain why upcasting is implicit and always safe
  • Downcast explicitly to reach members the parent type hides
  • Guard every downcast with `instanceof` to avoid ClassCastException
  • Recognise when a downcast is a design smell rather than a solution
1

Upcasting

Upcasting: looking at a Dog through Animal glasses

Upcasting is storing a child object in a parent-typed reference. You already did it: Animal a = new Dog(); It needs no syntax because it can never fail — a Dog *is* an Animal, so every Animal member exists on it. What you lose is *visibility*: the variable now only exposes the Animal vocabulary. The object is untouched; you have simply put on glasses that show fewer details.

Two directions, two rules

UpcastingDowncasting
Directionchild → parentparent → child
Syntaximplicit: Animal a = new Dog();explicit: Dog d = (Dog) a;
Can it fail?neveryes — ClassCastException at run time
Effecthides child-only membersreveals child-only members again
Typical usestoring mixed subclasses in one array/list; method parametersreaching a special capability of one subtype

Upcasting is what makes `Animal[]` possible

An array (or list) can only hold one declared type. Animal[] zoo = { new Dog(...), new Cat(...) } works because each element is silently upcast. Every collection of mixed subtypes in Java relies on this.

2

Downcasting

Downcasting: taking the glasses off

The Dog never stopped being a Dog. A cast is you telling the compiler what you already know — and taking responsibility if you are wrong.

Up, then back down

Main.java
1Animal a = new Dog("Rex");
2a.sound();
3
4Dog d = (Dog) a;
5d.fetch();
Animal a = new Dog("Rex");
Upcast. The object is a Dog; the variable shows the Animal view.
a.sound();
Legal (Animal declares it) and dispatches to Dog's override. No cast needed for overridden behaviour — a very common misunderstanding.
Dog d = (Dog) a;
Downcast: (Dog) is a promise to the compiler that this object really is a Dog. The compiler allows it because Dog is a subtype of Animal; the *JVM* verifies it at run time.
d.fetch();
Now the Dog-only method is visible. This is the only reason to downcast: to reach something the parent type does not declare.
A safe downcast

Run it. Then change the first line to `Animal a = new Animal("Generic");` and re-run — the cast now fails at run time, not compile time.

Output
Press Run to execute this example.
The dangerous version
Main.java
1Animal a = new Cat("Luna");
2Dog d = (Dog) a; // compiles fine...
3d.fetch(); // ...ClassCastException: Cat cannot be cast to Dog
The compiler cannot know what the reference will hold at run time, so it trusts your cast. If you are wrong the program crashes — which is why every downcast needs a guard.
3

instanceof & Casting

instanceof: ask before you cast

x instanceof Dog is a boolean test: *is the object referred to by x a Dog (or a subclass of Dog)?* It is the seat belt for downcasting. The safe pattern is always the same: ``java if (current instanceof Dog) { Dog dog = (Dog) current; dog.fetch(); } ` One extra detail worth knowing: null instanceof Dog is false`, never an error — so the check also protects you from a null reference.

Special treatment for one subtype only

Every animal makes a sound polymorphically; only dogs fetch. Add a Cat-only `scratch()` and an `instanceof Cat` branch.

Output
Press Run to execute this example.

Every downcast is a question about your design

One instanceof for a genuinely exceptional capability is fine. A *chain* of them means the behaviour belongs in the classes: add a method to the parent (or an interface) and override it. If you find yourself asking 'what type is this?' repeatedly, polymorphism is being bypassed.

Modern Java: pattern matching

Since Java 16 you can bind the variable inside the check: ``java if (current instanceof Dog dog) { dog.fetch(); } ` Same semantics, one line shorter, and impossible to get the cast wrong. The sandbox in this course uses the classic instanceof` + cast form, which is what university exams and most existing codebases still use — but recognise the newer syntax when you meet it.

Prove it — coding challenges

Common mistakes

WrongCasting in order to get the overridden behaviour: `((Dog) a).sound();`
WhyUnnecessary — `a.sound()` already runs Dog's version. Casts are only for members the parent does not declare.
FixCall `a.sound()` directly.
WrongDowncasting without an `instanceof` guard.
WhyIt compiles, then throws `ClassCastException` the first time the reference holds a different subtype.
Fixif (x instanceof Dog) { Dog d = (Dog) x; ... }
Wrong`Dog d = (Dog) new Cat("Luna");`
WhyCat and Dog are siblings — there is no inheritance relationship, so this cannot succeed (the compiler rejects it outright when the types are provably unrelated).
FixCast only along a real parent–child line.

Lesson playground

Free practice

A mixed team array: everyone works polymorphically, and only managers approve. Add an `Intern` whose `work()` prints something else — no branch needed for it.

Output
Press Run to execute this example.

Check understanding

Quiz

Question 1 of 5

What does this print?

Main.java
1class Device {
2 void turnOn() {
3 System.out.println("Device on");
4 }
5}
6
7class Phone extends Device {
8 @Override
9 void turnOn() {
10 System.out.println("Phone on");
11 }
12
13 void call() {
14 System.out.println("Calling...");
15 }
16}
17
18public class Main {
19 public static void main(String[] args) {
20 Device device = new Phone();
21 device.turnOn();
22
23 Phone phone = (Phone) device;
24 phone.call();
25 phone.turnOn();
26 }
27}

Summary

  • Upcasting (child → parent) is implicit and can never fail; it only hides child-only members.
  • Downcasting (parent → child) is explicit and can throw `ClassCastException`.
  • You never need a cast to get overridden behaviour — only to reach members the parent does not declare.
  • Guard downcasts with `instanceof`, and treat chains of `instanceof` as a missing override.