Lesson · Inheritance & Polymorphism
Type checking and casting: up is free, down is a promise
16 min readType Checking & Casting
Widening to a parent type never fails; narrowing back is an explicit promise the runtime verifies, crashing with ClassCastException when it is wrong. instanceof (with pattern binding) checks before you cast.
Two casts, one crash
The same cast syntax appears twice below; predict which line breaks, and when:
Shape a = new Circle(2); Circle ok = (Circle) a; // the object really is a Circle System.out.println(ok.radius); // 2.0 Shape b = new Square(3); Circle bad = (Circle) b; // the object is a Square System.out.println(bad.radius);
Predict: both lines compile; the compiler accepts any cast between related types. The second line fails at runtime, because casting is a promise about the object that actually shows up, and this one is a Square. The error message names both classes and is worth reading twice.
Two directions, two rules
Casting moves a reference along the inheritance chain. The two directions could not be more different:
| Direction | Example | Safety | Checked |
|---|---|---|---|
| Up (child → parent): called upcasting | Shape s = new Circle(2); | Always safe: every Circle IS-A Shape | Not checked; often written with no cast at all |
| Down (parent → child): called downcasting | Circle c = (Circle) s; | A promise: true only if the object really is that kind | At runtime, every time, by the JVM |
- Upcasting is the IS-A guarantee paying off: no syntax, no risk, no exception.
- Downcasting needs the cast
(Circle)to tell the compiler you accept the risk, and the runtime verifies your claim on each execution. - Downcast only when the parent's API is not enough: you need
radius, which only Circle offers. - Check before you cast.
if (s instanceof Circle c)both asks and names the object as a Circle, so no separate cast line is needed.
The compiler trusts relationships; the runtime checks objects. A cast between unrelated types is refused at compile time. A cast between related types always compiles, and the object gets the final word when the line runs.
Checking instead of crashing
The visual below runs both casts and the safe alternative. Notice that a failing check is not an error: instanceof answers false and the program walks on.
instanceofasks a yes/no question about the object at runtime; no answer ever throws.- Pattern matching (
x instanceof Circle c) binds the checked value to a name in one step; inside the if,cis a Circle. - Negated checks (
if (!(x instanceof Circle)) return;) let the compiler treat the rest of the method as safe. - A cast that lies throws
ClassCastException: class Square cannot be cast to class Circle: the message names the object's class first, the attempted type second.
Check first, cast second, prefer never. Every downcast is a small bet; instanceof turns the bet into a verified fact, and polymorphism often removes the need entirely.
Casting lane · up is free, down is a promise
Current statement
The reference, and the object behind it
The compiler sees the reference's type; the runtime sees the object's class. Casting is where the two have to agree.
Free
No check needed: every Circle IS-A Shape, so this can never fail.
Upcasting: a Circle object held through a Shape reference. No cast syntax, no risk, no exception possible. The compiler accepts it as a plain assignment.
The one place the choice bites back: equals
Equality implementations must be symmetric: a.equals(b) and b.equals(a) must agree. Two styles exist for the class check inside equals, and they trade off:
- `instanceof` style: open to subclasses; a careful subclass can participate, but a careless one breaks symmetry: in the classic
ColorPointcase the parent accepts the child while the child rejects the parent, sop.equals(cp)andcp.equals(p)disagree. - `getClass()` style: strict same-class equality (returns the object's runtime class). Symmetry is safe by construction, at the cost of a subclass never being equal to its parent.
- The safe default for value classes: use
getClass(); it cannot be defeated by a subclass you have not met yet. If you chooseinstanceof, the class should arguably befinal.
Whichever you choose, choose on purpose. The equals contract has more rules (reflexive, symmetric, transitive, consistent), and the Object Contracts chapter takes them apart; for now, remember that the class check is where symmetry dies or survives.
The casting playbook
Reaching for a cast, in order:
- Ask why the parent's API is not enough; if a method belongs to the parent's meaning, add it there and let polymorphism work.
- If the specific type is genuinely required, take it as far up as the declaration can: parameters of the specific type beat casts inside the body.
- Whenever a downcast survives, put an
instanceofcheck (pattern form) in front of it. - Treat
ClassCastExceptionas a design smell: it means somewhere a promise about the object was simply wrong. - In
equals, pick the class check deliberately:getClass()for strict value classes,instanceofwhen subclasses are meant to be equal.
Upcasting is communication; downcasting is a bet. Write code that deals in parent types, and the bets shrink to the few places where a feature is genuinely type-specific.
Up is free, down is a promise the runtime verifies
Every child IS-A parent, so widening costs nothing and never fails. Narrowing back needs a cast to reassure the compiler, and the JVM checks the object each time the line runs, throwing ClassCastException when the claim is false. instanceof with pattern binding checks and names the object in one move, which is the habit to build.
Interview angles
What do upcasting and downcasting each mean for safety?+
Upcasting (child to parent) is always safe and usually implicit; downcasting (parent to child) is an explicit promise, verified by the runtime on every execution.
The compiler allows any cast between related types because related types can overlap; only the object knows the truth. Upcasting never needs a check; downcasting deserves one, and pattern-matching instanceof combines check and cast.
Shape s = new Circle(2); // upcast: free Circle c = (Circle) s; // downcast: compiles, runtime verifies if (s instanceof Circle ok) { /* ok is already a Circle */ }
Common misconception: That a cast converts the object. It never touches the object; it re-labels the reference after a check (or throws when the check fails).
Follow-up: When is a downcast genuinely needed?
When exactly does `ClassCastException` happen, and what does it mean?+
At runtime, when a cast's promise is false: the object that arrived is not an instance of the type you cast to. The message names both classes.
Compilation proves only that the cast is possible in principle, since some object of the hierarchy might match. The JVM performs the real check as the line executes, so the same cast can succeed in a test and fail in production when different objects flow through.
// ClassCastException: class Square cannot be cast to class Circle Circle bad = (Circle) new Square(3); // compiled fine, failed at runtime
Common misconception: That a successful compile means a safe cast. Compilation checked the type names, not the object; the runtime is where the promise is kept or broken.
Follow-up: How would you defend a cast so the exception becomes impossible?
What does pattern matching for `instanceof` add?+
It checks and binds in one step: if (o instanceof Circle c) makes c a Circle inside the branch, with no separate cast and no way to check the wrong variable.
The compiler scopes the binding precisely (available only where the check proves it), which also makes negative checks safe: after if (!(o instanceof Circle c)) return; the rest of the method may use c directly.
if (shape instanceof Circle c) { System.out.println(c.radius); // no cast, no repeat of the variable }
Common misconception: That the pattern is sugar for a cast you would have written anyway. It is stronger: the cast can never drift from the check, because there is none written separately.
Follow-up: Where else does pattern matching appear in modern Java?
If polymorphism is so good, why does casting exist?+
Some operations exist only on the specific type: a Circle's radius is not part of Shape's contract. Casting, guarded by a check, is the escape hatch for those moments.
The healthy pattern is a small number of checked downcasts at the boundary where a general pipeline meets a type-specific feature, and everything between those points written against parent types. A codebase full of casts usually misses a method on the parent.
if (shape instanceof Circle c) { total += Math.PI * c.radius * c.radius; // type-specific maths }
Common misconception: That casts are how you 'use' inheritance. Casting is the exception, not the mechanism; polymorphism is the mechanism.
Follow-up: How do you shrink the number of casts in a design?
Why does `equals` care about `getClass()` versus `instanceof`?+
Symmetry. instanceof lets a subclass be equal to its parent while the parent is not equal to it (the ColorPoint case); getClass() demands the exact same class and cannot be defeated that way.
The contract says a.equals(b) and b.equals(a) must agree. With instanceof, a subclass that adds state breaks symmetry: the parent's equals accepts the child (it is-a parent), while the child's stricter equals rejects the parent. getClass() is the safe default for value classes; instanceof suits hierarchies that are final or designed for extension together.
p.equals(cp); // true: Point accepts the ColorPoint, it is-a Point cp.equals(p); // false: ColorPoint's stricter equals rejects the plain Point // symmetric equality just broke: the pair disagrees depending on who asks
Common misconception: That the class check is a style preference. It decides whether the equals contract holds under subclassing, which collections and tests actually depend on.
Follow-up: What happens when symmetry is broken inside a HashSet?