Skip to content

Java OOP

0/36 lessons · 0% complete

— XP

Java OOP · Module 8

One reference, many forms

Animal animal = new Dog(); — dissected in four questions

24m60 XP
→→→

What you'll be able to do

  • Define polymorphism in terms of references and objects, not slogans
  • Answer the four questions about any `Parent p = new Child();` line
  • Distinguish compile-time polymorphism from runtime polymorphism
  • Replace a chain of type checks with a polymorphic call
1

Polymorphism

What polymorphism actually buys you

Polymorphism means 'many forms'. In practice it means: your `for` loop never has to know which subclass it is holding.

You already built polymorphism in Module 7 — this lesson names it and pushes it further. Polymorphism = the ability of one reference type to refer to objects of many different classes, and for the *object* to decide which behaviour runs. Two ingredients make it possible: 1. Inheritance (or interfaces) — so a Dog can legally be stored in an Animal variable. 2. Overriding — so Dog has its own version of the method to run. Without it, every new type forces you to edit existing code. With it, existing code keeps working and new types simply plug in.

One power button, many devices

A universal remote has one power() button. Point it at the TV and the TV turns on; point it at the air conditioner and the AC starts. The button never changed — the *device* decides what 'power' means. Your code is the button; the object is the device.

`Animal animal = new Dog();` — the four questions

QuestionAnswerWhy it matters
What is the reference type?Animal — the declared type of the variableit defines the *vocabulary*: the set of members you are allowed to use
What is the real object type?Dog — what new created on the heapthe object keeps this identity for its whole life
What can I access?only what Animal declares (sound(), eat(), ...) — *not* Dog-only membersanimal.fetch() is a compile error even though the object has fetch()
Which method runs?the Dog override, chosen at run timethis is dynamic method dispatch — the object always wins

Reference type = what you may say. Object type = what actually happens. Every polymorphism puzzle is solved by answering these four questions in order.

The payoff: a loop that does not care

Add a `Cow extends Animal` overriding `sound()` with 'Moo', then add `new Cow("Bella")` to the array. The loop stays untouched — that is the entire point.

Output
Press Run to execute this example.

The same feature, written twice

Without polymorphism

a chain that grows forever

Main.java
1void speak(Object a) {
2 if (a instanceof Dog) {
3 System.out.println("Woof");
4 } else if (a instanceof Cat) {
5 System.out.println("Meow");
6 }
7 // add Cow → edit this method
8}
  • Every new type edits existing, tested code
  • Forget one branch and it silently does nothing
  • Behaviour lives far away from the class it belongs to

With polymorphism

closed for modification, open for extension

Main.java
1void speak(Animal a) {
2 a.sound();
3}
4
5// add Cow → write Cow.sound()
6// this method never changes
  • New types plug in without touching callers
  • The compiler forces each subclass to supply behaviour (Module 10)
  • Each class owns its own logic

Interview one-liner

“Polymorphism lets me program against an abstraction instead of a concrete class, so behaviour is selected by the object at run time and new subtypes require no changes to existing code.” Then give the Animal[] loop or the Payment example — a concrete example after the definition is what separates a strong answer from a memorised one.

2

Compile-time vs Runtime

Compile-time vs runtime polymorphism

Java makes two kinds of 'many forms' — and only one of them is decided while your program is running.

The two kinds

Compile-time (static)Runtime (dynamic)
Mechanismmethod overloading (Module 9)method overriding
Decided bythe compilerthe JVM
Based onthe declared types of the argumentsthe actual class of the object
Also calledearly / static bindinglate / dynamic binding, dynamic dispatch
Needs inheritance?noyes (or an interface)
Exampleadd(2, 3) vs add(2.5, 3.5)animal.sound() on a Dog

When people say 'polymorphism' without qualification, they almost always mean the runtime kind — that is the one that changes how you design systems. Overloading is a convenience for callers; overriding is a lever for architecture. A useful way to keep them apart: overloading asks *'which method did you mean?'* and is answered before the program runs. Overriding asks *'whose version of this method?'* and can only be answered once a real object exists.

Both kinds in four lines
Main.java
1Animal a = new Dog();
2
3a.sound(); // runtime: Dog's override runs
4
5Calculator c = new Calculator();
6c.add(2, 3); // compile-time: add(int, int) chosen
7c.add(2.5, 3.5); // compile-time: add(double, double) chosen
Two decisions, two moments. Mixing them up is the single most common source of confusion in OOP exams.

Common mistakes

WrongBelieving polymorphism means 'a method with many versions' (overloading).
WhyThat is only the compile-time kind; the important one is overriding through a parent reference.
FixSay which kind you mean: overloading = compile time, overriding = runtime.
WrongUsing `instanceof` chains to pick behaviour for each subclass.
WhyYou are re-implementing dynamic dispatch by hand, badly.
FixGive the parent a method and override it in each subclass; call it once.
WrongDeclaring `Dog dog = new Dog();` everywhere and passing `Dog` into every method.
WhyYour methods now only work for dogs; nothing is reusable.
FixAccept the most general type that does the job (`void speak(Animal a)`).

Lesson playground

Free practice

`report(Shape)` is written once against the parent type. Add a `Triangle` (area = base * height / 2) and report it — without editing `report`.

Output
Press Run to execute this example.

Check understanding

Quiz

Question 1 of 5

Dog overrides one method and inherits the other. What does this print?

Main.java
1class Animal {
2 void sound() {
3 System.out.println("Some sound");
4 }
5
6 void eat() {
7 System.out.println("Animal eats");
8 }
9}
10
11class Dog extends Animal {
12 @Override
13 void sound() {
14 System.out.println("Woof");
15 }
16
17 void fetch() {
18 System.out.println("Fetching");
19 }
20}
21
22public class Main {
23 public static void main(String[] args) {
24 Animal animal = new Dog();
25 animal.sound();
26 animal.eat();
27 }
28}

Summary

  • Polymorphism = one reference type, many object types, behaviour chosen by the object.
  • Reference type decides what you can call; the object decides what runs.
  • Overloading is compile-time polymorphism; overriding is runtime polymorphism.
  • A polymorphic call replaces an `instanceof` chain and survives new subclasses unchanged.