Java OOP · Module 8
Upcasting, downcasting, instanceof
Widening the view safely — and narrowing it carefully
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
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
| Upcasting | Downcasting | |
|---|---|---|
| Direction | child → parent | parent → child |
| Syntax | implicit: Animal a = new Dog(); | explicit: Dog d = (Dog) a; |
| Can it fail? | never | yes — ClassCastException at run time |
| Effect | hides child-only members | reveals child-only members again |
| Typical use | storing mixed subclasses in one array/list; method parameters | reaching 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.
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
(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.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.
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.
Every animal makes a sound polymorphically; only dogs fetch. Add a Cat-only `scratch()` and an `instanceof Cat` branch.
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
Casting in order to get the overridden behaviour: `((Dog) a).sound();`Downcasting without an `instanceof` guard.`Dog d = (Dog) new Cat("Luna");`Lesson playground
A mixed team array: everyone works polymorphically, and only managers approve. Add an `Intern` whose `work()` prints something else — no branch needed for it.
Check understanding
Quiz
Question 1 of 5
What does this print?
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.