Why It Exists#
StudyBuddy has three kinds of question. Without OOP, every piece of code that touches a question needs an
if … else if … chain on its type — in grading, in display, in export. Add a fourth type and you must find and edit every chain.
Polymorphism deletes all of those chains. You write q.grade(answer) once, and each question grades itself in its own way.
The Plain Picture#
Picture 1 — the TV remote. Press the power button at a Sony TV and the Sony turns off its way; press it at an LG and the LG does it its way. The button is the same. What actually happens depends on which TV is on the other end. You don't need to know the brand to press it.
Picture 2 — the sticker on a box. A box arrives at a warehouse with a sticker that says only "FRAGILE ITEM".
First, a gatekeeper checks the box. They read only the sticker. Ask them "can I plug this in?" and they say "No idea — the sticker just says fragile item. I'll only allow what every fragile item can do: handle with care."
Later, a packer opens the box and sees what is really inside — a glass lamp — and handles it the lamp's way.
| In the picture | In Java |
|---|---|
| the sticker | the declared type — the type written on the variable |
| what's inside the box | the actual object on the heap |
| the gatekeeper, before anything moves | the compiler (javac), before the program runs |
| the packer, working with the real thing | the JVM, while the program runs |
Keep this picture. It answers nearly every confusing question in this chapter.
The Real Names#
Polymorphism (Greek for "many shapes") — one call, many behaviours.
Declared type (also reference type or static type) — the type written on the variable:
QuestioninQuestion q = …. The compiler knows it.Actual type (also runtime type or dynamic type) — the class of the object the variable really points to, e.g.
ShortAnswer. Known only when the program runs.q.getClass()tells you.Dynamic dispatch (also late binding) — choosing which version of an overridden method runs, at run time, from the actual type.
Upcasting — looking at a child object through a parent-type variable. Automatic and always safe.
Downcasting — going back from a parent-type variable to a child type. Needs a written cast
(Type), is checked at run time, and can fail with aClassCastException.
Under the Hood#
Step 1 — Where things live: stack and heap (a two-minute recap)#
From Classes, Objects and Memory Ch 4:
The heap is the big shared area where every object lives.
newcreates objects there; the garbage collector removes them when nothing refers to them any more.The stack gives every running method a small private notepad called a stack frame, which holds its local variables. A variable of a class type never holds the object itself — it holds a reference: the object's address, like a card with a house's address on it.
When a method returns, its frame is thrown away. The objects stay on the heap while something still refers to them.
Now run one line:
Question q = new ShortAnswer("H2O is commonly called?", 10, "water"); STACK (main's frame) HEAP
┌──────────────────────┐ ┌────────────────────────────────────────┐
│ q type: Question │ │ ONE ShortAnswer object │
│ ●────────────────┼─────────▶│ ┌──────────────────────────────────┐ │
└──────────────────────┘ │ │ header -> class is ShortAnswer │ │
│ ├──────────────────────────────────┤ │
│ │ points = 10 parent part │ │
│ │ text = "H2O..." (Question) │ │
│ ├──────────────────────────────────┤ │
│ │ expected = "water" child part │ │
│ └──────────────────────────────────┘ │
└────────────────────────────────────────┘Three facts in this picture:
One object, not two.
new ShortAnswer(...)does not create aQuestionobject plus aShortAnswerobject. It creates one object with room for all the fields — the parent's (text,points) and the child's (expected).super(text, points)(Ch 2) just fills in the parent's part of that same object.The object knows its real class. Every object starts with a hidden header, and part of the header points to the object's class. That is how the JVM can always find the actual type, whatever the variable says.
The variable only holds an address. The declared type
Questionis information for the compiler. At run time,qis just an arrow to the object.
Proof, from Java 21.0.8 (listing the fields of the object's class and its parents, then asking the JVM where each field sits):
fields inside ONE ShortAnswer object: expected (declared in ShortAnswer) text (declared in Question) points (declared in Question)
byte offsets inside the object: text@16 points@12 expected@20Bytes 0–11 are the header. The parent's fields sit at bytes 12 and 16, the child's field at byte 20 — one 24-byte object.
Step 2 — Two checkers: first the compiler, then the JVM#
This is the idea that makes everything click. Every method call is checked by two different "people", at two different times.
┌─ BEFORE the program runs ──────────────────────────────────────────┐
│ COMPILER (javac) │
│ sees: only the declared type of the variable (the sticker) │
│ asks: "Does Question have a method grade(String)?" │
│ yes -> writes "call grade on whatever object q points to" │
│ no -> compile error; the program is never built │
└────────────────────────────────────────────────────────────────────┘
│
▼
┌─ WHILE the program runs ───────────────────────────────────────────┐
│ JVM │
│ sees: the actual object on the heap (reads its header) │
│ asks: "This is a ShortAnswer. Which grade() does it use?" │
│ runs: that version │
└────────────────────────────────────────────────────────────────────┘Why can't the compiler just look inside? Because often nobody knows what is inside until the program runs:
Question q = loadFromDatabase(id); // MCQ? true/false? short answer? Only known at run time.So the compiler plays safe: it allows only what every possible Question can do.
Now compare two calls on the same q:
| Call | Compiler (sees Question) | JVM (finds a ShortAnswer) | Result |
|---|---|---|---|
q.grade("water") | Question has grade ✔ | runs grade, which calls ShortAnswer's isCorrect | works: 10 |
q.hint() | Question has no hint ✘ | never gets here | compile error |
Err.java:7: error: cannot find symbol
q.hint();
^
symbol: method hint()
location: variable q of type QuestionRead the last line: "variable q of type Question". The compiler is telling you it looked only at the sticker.
Step 3 — A full trace of quiz.get(2).grade(" Water ")#
What happens, step by step, when the grading loop reaches the short-answer question:
Compile time.
quizis aList<Question>, soquiz.get(2)has declared typeQuestion. DoesQuestionhavegrade(String)? Yes. The compiler writes an instruction that means "callgrade; pick the version at run time". Here it is in the compiled file, shown byjavap -c(a JDK tool that prints compiled bytecode):Output invokevirtual #58 // Method Question.grade:(Ljava/lang/String;)Iinvokevirtual= "call an overridable method; choose the version from the actual object".Run time. The JVM follows the reference to the heap and reads the header:
ShortAnswer. ShortAnswer did not overridegrade, so it uses the one it inherited fromQuestion.Inside
grade. The body isreturn isCorrect(answer) ? points : 0;. WritingisCorrect(answer)is short forthis.isCorrect(answer)— andthisis the same ShortAnswer object. The bytecode ofgradeshows it:Output 0: aload_0 // load "this" 1: aload_1 // load "answer" 2: invokevirtual #17 // Method isCorrect:(Ljava/lang/String;)Zinvokevirtualagain, so the JVM looks at the actual class ofthisand runs ShortAnswer'sisCorrect." Water ".trim().equalsIgnoreCase("water")istrue, sogradereturnspoints, which is10.
The stack while isCorrect is running (main has already scored 10 + 5 from the first two questions):
STACK (top = running now) HEAP ┌───────────────────────────────┐ │ isCorrect frame │ │ this ●──────────────────────┼──┐ ├───────────────────────────────┤ │ ┌──────────────────────┐ │ grade frame │ ├────▶│ ShortAnswer object │ │ this ●──────────────────────┼──┘ │ points = 10 │ ├───────────────────────────────┤ │ text, expected │ │ main frame │ └──────────────────────┘ │ quiz ● total = 15 │ └───────────────────────────────┘
Two frames, two this variables, one object. this always means "the object this method was called on", so every call made
through this is dispatched on the real object.
Step 4 — Upcasting and downcasting, properly#
The picture: casting changes the sticker. It never changes what is in the box.
ShortAnswer sa ────┐
├────▶ [ one ShortAnswer object on the heap ]
Question q ────┘
through sa (sticker "ShortAnswer"): grade() describe() hint()
through q (sticker "Question"): grade() describe()Upcasting — going up the family tree, child to parent:
ShortAnswer sa = new ShortAnswer("H2O is commonly called?", 10, "water");
Question q = sa; // upcast: automatic, no "(Question)" neededIt is always safe, because a ShortAnswer is a Question: it is guaranteed to have every method a Question has. So Java does it
silently. Nothing in the object is lost; you just see less of it through q.
You upcast all the time without noticing: putting a MultipleChoice into a List<Question>, or passing a ShortAnswer to a
method whose parameter is Question.
Downcasting — going back down, parent to child:
ShortAnswer back = (ShortAnswer) q; // downcast: you must write the cast
back.hint(); // Hint: starts with wWhy must you write it? Because a Question might not be a ShortAnswer. Writing (ShortAnswer) is a promise to the compiler:
"trust me, this one is a ShortAnswer." The compiler accepts the promise if it is possible, and the JVM checks it at run time:
(ShortAnswer) q
│
▼
compile time: could a Question ever be a ShortAnswer?
yes (ShortAnswer extends Question) -> allowed
│
▼
run time: JVM reads the object's header
│
┌───────┴─────────────────┐
▼ ▼
it IS a ShortAnswer it is something else, e.g. MultipleChoice
-> cast succeeds -> ClassCastException, the program stops hereBreaking the promise (real output):
ClassCastException: class MultipleChoice cannot be cast to class ShortAnswer (MultipleChoice and ShortAnswer are in unnamed module of loader 'app')A cast that could never work is stopped before the program runs. No class can be both a Question and a String (String is
final, so nothing can extend it):
String s = (String) q;Err.java:8: error: incompatible types: Question cannot be converted to StringProof that casting never changes the object (real output):
same object? q == back -> true, identityHashCode q=61bbe9ba back=61bbe9ba== on references compares addresses. Same address means same object. The cast only copied the address into a variable with a
different sticker; nothing on the heap moved or changed.
The safe way to downcast: check first.
if (q instanceof ShortAnswer sa) {
// "is the real object a ShortAnswer? if yes, give it to me as sa"
System.out.println(sa.hint()); // Hint: starts with w
}instanceof asks about the actual type. This pattern form (Java 16+) checks, casts and creates the new variable in one step, so
a ClassCastException can't happen.
Java 21's switch can do the same for several types at once:
String kind = switch (q) {
case MultipleChoice mc -> "MCQ";
case TrueFalse tf -> "True/False";
case ShortAnswer sa -> "Short answer (" + sa.hint() + ")";
default -> "unknown";
};For the three quiz questions this prints MCQ, True/False and Short answer (Hint: starts with w). With a sealed Question
(Modern Java Ch 10) the compiler knows every subtype and you can drop default.
| Upcasting | Downcasting | |
|---|---|---|
| Direction | child → parent (ShortAnswer → Question) | parent → child (Question → ShortAnswer) |
| How you write it | automatic: Question q = sa; | explicit: (ShortAnswer) q |
| Safe? | always | only if the object really is that type |
| Checked | nothing to check | at compile time (is it possible?) and at run time (is it true?) |
| Can fail with | never fails | ClassCastException |
| Changes the object? | no — only the sticker | no — only the sticker |
| Use it for | general code: lists, parameters, return types | rare cases where you need child-only methods back |
When do you really need a downcast? Rarely:
inside
equals(Object o), which receives anObjectand must get your own type back (Ch 8);when an older API hands you a plain
Object;when handling messages or events of mixed types (use a
switchwith patterns).
If you find instanceof checks spread all over your code, the behaviour probably belongs in an overridden method, so that dispatch
picks it for you:
// asks each object what it is, then decides for it
if (q instanceof MultipleChoice) { ... } else if (q instanceof ShortAnswer) { ... }
// tells the object to do the job, and lets it decide
q.grade(answer);The rule of thumb is called "Tell, don't ask."
Step 5 — Compile-time vs run-time polymorphism#
| Kind | Also called | Decided | Using | Example |
|---|---|---|---|---|
| Overloading (Java Basics Ch 7) | compile-time or static polymorphism, early binding | when compiling | the declared types of the arguments | add(int,int) vs add(double,double) |
| Overriding (Ch 3) | run-time or dynamic polymorphism, late binding | while running | the actual type of the object | q.isCorrect(a) |
These are not dispatched at run time — the compiler fixes them from the declared type:
staticmethods (Ch 3: hidden, not overridden);privatemethods (not inherited, so there is nothing to override);fields (Gotcha 1 below);
which overload to call (Gotcha 2 below).
(Generics — one List<T> that works for any T — are sometimes called a third kind, parametric polymorphism:
Exceptions and Generics.)
But wait…
The questions people actually get stuck on.
"The compiler only checks the declared type — so how does q.grade() end up running ShortAnswer's isCorrect?"
The compiler checks whether you may call grade (Question has it ✔). It does not choose the version: it writes "call it on
whatever object is there" (invokevirtual). At run time the JVM looks at the real object. Inside grade, isCorrect(answer) means
this.isCorrect(answer), and this is the ShortAnswer. Two checkers, two different jobs (Step 2).
"Then why does q.hint() fail, if the object really is a ShortAnswer?"
Because the compiler's check comes first, and the sticker says Question, which has no hint. The program is never built, so the
JVM never gets the chance to look inside.
"Does new ShortAnswer(...) make a Question object and a ShortAnswer object?"
No. One object, with room for the parent's fields and the child's fields (Step 1). super(text, points) fills in the parent's part
of that same object.
"Can the child use the parent's private fields?"
They exist inside the child object and take memory, but the child's code can't name them. It goes through the parent's
constructor and methods instead. protected fields can be used directly by the child.
"Does casting turn the object into another type?"
No. It copies the address into a variable with a different sticker. Same object, same header, same fields (Step 4 proof).
"Why would I write Question q = new ShortAnswer(...) and lose hint()?"
So that one piece of code handles every kind of question: the grading loop, a List<Question>, a method print(Question q). They
all work for MCQ, true/false, short answer — and for a type someone adds next year — without changing a line.
"Isn't looking up the method at run time slow?"
It is one table lookup, and the JIT usually removes even that (Advanced, below).
Go deeperOptional, read it after the basics click
How dynamic dispatch works inside the JVM#
Each class has a hidden method table (often called a vtable): a list of pointers to the code for each of its methods. A
subclass's table copies the parent's and replaces the entries it overrides. (Q = Question's code, MC = MultipleChoice's,
TF = TrueFalse's; none = abstract, no code.)
Question's table MultipleChoice's table TrueFalse's table ┌───────────────────┐ ┌───────────────────┐ ┌───────────────────┐ │ grade -> Q │ │ grade -> Q │ │ grade -> Q │ │ isCorrect -> none │ │ isCorrect -> MC │ │ isCorrect -> TF │ │ describe -> Q │ │ describe -> MC │ │ describe -> Q │ └───────────────────┘ └───────────────────┘ └───────────────────┘
Every object remembers its class through its header. q.isCorrect(a) becomes "go to this object's class, open its table at
slot isCorrect, jump there" — one extra memory lookup.
Which call instructions dispatch#
| Bytecode | Used for | Version chosen |
|---|---|---|
invokevirtual | instance methods called through a class type | at run time, from the actual class |
invokeinterface | methods called through an interface type (Ch 6), e.g. List.get | at run time, from the actual class |
invokestatic | static methods | at compile time |
invokespecial | constructors and super.method() calls | at compile time — exactly the one named |
Since Java 11, javac also uses invokevirtual for calls to a class's own private methods (checked here with javap:
invokevirtual … Method secret:()I). The JVM still runs exactly that method, because a private method can't be overridden.
Why it is still fast: the JIT#
The JIT (How Computers Work Ch 8) watches every call site. If a site has only ever seen one actual type (monomorphic), it replaces the table lookup with a direct call and often copies the method body in place (inlining). With two types (bimorphic) it adds a quick type test. Only with many types (megamorphic) does it fall back to the full lookup. So in practice polymorphism costs almost nothing. (This is HotSpot's documented behaviour; it is not measured in this file.)
Why the parent's fields never move#
Code compiled for Question reads points at one fixed position (byte 12 above) — it has no idea which subclass it is looking at.
So the JVM gives the parent's fields the same positions in every subclass object and places the child's fields elsewhere. That
is why a ShortAnswer can be used anywhere a Question is expected with no conversion at all.
Gotchas
Fields are not polymorphic
class Parent {
String name = "parent field";
String who() {
return "parent method";
}
}
class Child extends Parent {
String name = "child field";
@Override
String who() {
return "child method";
}
}
Parent p = new Child();p.name -> parent field | p.who() -> child method | ((Child) p).name -> child fieldThe method was dispatched on the real object; the field was chosen by the sticker. The Child object really holds two name
fields. Keep fields private and this never bites you.
The overload is chosen by the declared type
a classic trick question.
static String show(Question q) {
return "show(Question) chosen";
}
static String show(ShortAnswer s) {
return "show(ShortAnswer) chosen";
}
Question q = new ShortAnswer("H2O is commonly called?", 10, "water");
show(q);show(Question) chosenOverloads are picked at compile time, and the compiler sees only Question. Only the object before the dot (q.method()) is
dispatched at run time — never the arguments. (Languages that also dispatch on arguments have multiple dispatch; Java doesn't.
The Visitor pattern, Behavioural Patterns (coming soon), is the usual workaround.)
Don't call overridable methods from a constructor
abstract class Badge {
Badge() {
System.out.println("Badge constructor prints: " + label());
}
abstract String label();
}
class NameBadge extends Badge {
private final String owner;
NameBadge(String owner) {
super();
this.owner = owner;
}
@Override
String label() {
return "owner=" + owner;
}
}
new NameBadge("Ravi");Badge constructor prints: owner=nullThe parent constructor runs first (Ch 2), and dispatch already goes to the child's label() — but owner has not been set yet,
even though it is final. Call only private or final methods from constructors.
Did you know?
getClass()always tells the truth.q.getClass().getSimpleName()printedShortAnswerfor a variable declared asQuestion.In Java every instance method can be overridden unless you say
final. In C++ and C# it's the opposite: you must mark a methodvirtualto get dynamic dispatch.Arrays have a hole that lists don't. A
ShortAnswer[]is aQuestion[], so this compiles:Java Question[] arr = new ShortAnswer[2]; arr[0] = new TrueFalse("Sky is green", 5, false);Output ArrayStoreException: TrueFalseThe compiler saw
Question[]and allowed it; the JVM knows the real array holds only ShortAnswers and refuses at run time. AList<ShortAnswer>cannot be used as aList<Question>at all, so generics catch this at compile time (Exceptions and Generics).Python and JavaScript get polymorphism without inheritance. If an object has a
grademethod, you can call it — "duck typing" (Python OOP and Protocols (coming soon)).
Check yourself
11 questionsRecall
What is polymorphism, in one line?
Show answerHide answer
The same method call runs a different version depending on the actual object.
State the golden rule about the declared type and the actual type.
Show answerHide answer
The declared type decides what you may call; the actual type decides which version runs.
After Question q = new ShortAnswer(...), what is on the stack and what is on the heap?
Show answerHide answer
Stack: the variable q, holding a reference (an address). Heap: one ShortAnswer object — a header pointing to its class, the
parent's fields text and points, and the child's field expected.
Upcasting vs downcasting: which one is automatic, which one can fail, and with what exception?
Show answerHide answer
Upcasting is automatic and always safe. Downcasting needs (Type) and throws ClassCastException if the object isn't that type.
Name four things Java decides at compile time rather than at run time.
Show answerHide answer
Static method calls, private method calls, field access, and which overload to call.
Why is a call through this inside a parent method still dispatched to the child's version?
Show answerHide answer
Because isCorrect(answer) is really this.isCorrect(answer), this is the real object, and the call uses invokevirtual.
Predict the output
Predict the output — question 7
Question q = new TrueFalse("DNA is a protein", 5, false);
System.out.println(q.grade("false") + " " + q.getClass().getSimpleName());Show answerHide answer
5 TrueFalse — grade dispatches to TrueFalse.isCorrect("false"), which is true, so 5 points; getClass() gives the actual
type.
Using Parent and Child from Gotcha 1:
Parent p = new Child();
System.out.println(p.name + " / " + p.who());Show answerHide answer
parent field / child method.
Compile error, run-time exception, or fine?
Object o = "hello";
Integer n = (Integer) o;Show answerHide answer
It compiles (an Object might be an Integer), then throws at run time: class java.lang.String cannot be cast to class java.lang.Integer.
When does this fail — at compile time or at run time?
Question q = new MultipleChoice(
"Powerhouse of the cell? A) Mitochondria B) Nucleus",
10,
'A'
);
ShortAnswer s = (ShortAnswer) q;Show answerHide answer
At run time, with ClassCastException. The compiler allows it because a Question could be a ShortAnswer.
Spot the problem
Spot the problem — question 11
for (Question q : quiz) {
if (q instanceof ShortAnswer) total += ((ShortAnswer) q).grade(answer);
else if (q instanceof MultipleChoice) total += ((MultipleChoice) q).grade(answer);
else if (q instanceof TrueFalse) total += ((TrueFalse) q).grade(answer);
}Show answerHide answer
It works, but every if and cast is pointless — grade is already dispatched on the real object. Replace the whole block with
total += q.grade(answer);. As written, it also silently gives 0 points to any new question type.
Interview questions
"What is polymorphism? Give a real example."
"One call, many behaviours: the same method call runs different code depending on the actual object. In a quiz app, Question has
isCorrect, and each subclass overrides it. The grading loop just calls q.grade(answer) with no type checks, so a new question
type means writing one class — that's the Open/Closed principle."
"Compile-time vs run-time polymorphism?"
"Compile-time is overloading: the compiler picks the method from the declared types of the arguments. Run-time is overriding: the JVM picks the version from the actual object, through dynamic dispatch."
"How does the JVM implement dynamic dispatch?"
"The compiler emits invokevirtual (or invokeinterface). Each object's header points to its class, and each class has a method
table where overridden entries point to the subclass's code. The call is one lookup in that table, and the JIT usually turns it into
a direct, inlined call when a call site only ever sees one type."
"Explain upcasting and downcasting. When do you get a ClassCastException?"
"Upcasting is using a child object through a parent-type reference — automatic and always safe. Downcasting goes back to the child
type with an explicit cast. The compiler allows it if it's possible; the JVM checks the real type at run time and throws
ClassCastException if it's wrong. I use instanceof patterns to make it safe — and if I need many of them, I move the behaviour
into an overridden method."
"Are fields polymorphic? Static methods?"
"No. Field access and static calls are resolved from the declared type at compile time. A same-named field or static method in a subclass only hides the parent's."
"With show(Question) and show(ShortAnswer), what does show(q) call when Question q = new ShortAnswer()?"
"show(Question). Overloads are chosen at compile time from the declared type. Only the receiver — the object before the dot — is
dispatched at run time."
"Why shouldn't a constructor call an overridable method?"
"The parent constructor runs before the child's fields are set, but dispatch already goes to the child's override, so the override
sees null or 0 — even for final fields."