01 / 21

Polymorphism
in Java

Learn how one reference type can point to many object forms: the core principle that makes object-oriented code flexible and extensible.

Java Object-Oriented Programming

What Is Polymorphism?

Polymorphism comes from Greek: poly (many) + morph (form). In Java, it means a single variable of a superclass type can refer to objects of different subclass types, and the correct method is called based on the actual object, not the declared type.

Why Polymorphism Matters

Flexibility
Write methods that accept a superclass parameter and they work with every subclass: present and future.
Extensibility
Add new subclasses without changing any existing code that uses the superclass reference.
Simplicity
One unified interface replaces dozens of if/else type checks: cleaner, shorter, fewer bugs.

The Inheritance Foundation

Animal speak() Dog "Woof!" Cat "Meow!" Bird "Tweet!" @Override speak() @Override speak() @Override speak() Each subclass provides its own version of speak()

The Core Rule

// Superclass reference, subclass object
Animal myPet = new Dog();
myPet.speak();  // prints "Woof!"
1
Compile time: Java checks that Animal has a speak() method. It does, so the code compiles.
2
Run time: The JVM sees the actual object is a Dog and calls Dog's version of speak().
3
Result: The output is "Woof!", not the generic Animal version.

Compile-Time vs Run-Time Type

Animal myPet = new Dog (); Compile-time type (declared type) Run-time type (actual object) Method availability: checked by compile-time type · Method body: selected by run-time type

Overloading vs Overriding

Overloading Overriding
Where Same class Subclass re-defines superclass method
Signature Same name, different parameters Same name, same parameters
Resolved at Compile time Run time
Polymorphism type Static (compile-time) Dynamic (run-time)
Annotation None required @Override recommended

How to Apply Polymorphism

1
Create a superclass (or interface) with the method you want to be polymorphic.
2
Extend the superclass in one or more subclasses.
3
Override the method in each subclass with its own behavior.
4
Declare a variable using the superclass type, but assign a subclass object.
5
Call the method through the superclass reference: the JVM dispatches to the correct subclass version automatically.

Example 1: Shape Area

class Shape {
    public double area() {
        return 0;
    }
}

class Circle extends Shape {
    double radius;
    public Circle(double r) { radius = r; }

    @Override
    public double area() {
        return Math.PI * radius * radius;
    }
}

class Rectangle extends Shape {
    double w, h;
    public Rectangle(double w, double h) { this.w=w; this.h=h; }

    @Override
    public double area() {
        return w * h;
    }
}

Using the Shape Reference

public static void printArea(Shape s) {
    System.out.println("Area: " + s.area());
}

// In main:
Shape c = new Circle(5);
Shape r = new Rectangle(4, 6);

printArea(c);  // Area: 78.54...
printArea(r);  // Area: 24.0

Example 2: Polymorphic Arrays

Animal[] pets = new Animal[3];
pets[0] = new Dog();
pets[1] = new Cat();
pets[2] = new Bird();

for (Animal a : pets) {
    a.speak();  // each calls its own version
}
Dog Cat Bird Animal[] pets "Woof!" "Meow!" "Tweet!"

Example 3: Method Parameters

class Vehicle {
    public String fuelType() { return "Unknown"; }
}
class ElectricCar extends Vehicle {
    @Override
    public String fuelType() { return "Electric"; }
}
class GasTruck extends Vehicle {
    @Override
    public String fuelType() { return "Gasoline"; }
}

public static void refuel(Vehicle v) {
    System.out.println("Fuel: " + v.fuelType());
}

refuel(new ElectricCar());  // Fuel: Electric
refuel(new GasTruck());      // Fuel: Gasoline

What You Cannot Do

Animal a = new Dog();

a.speak();   // ✓ Animal has speak()
a.fetch();   // ✕ COMPILE ERROR: Animal has no fetch()

How the JVM Decides

a.speak() is called Compiler: Does Animal have speak()? ✓ JVM: What is the actual object type? Dog Execute Dog.speak() → "Woof!" Compile Time Run Time

Common Mistakes

✕ Calling subclass-only methods
Using a superclass reference and calling a method that only exists in the subclass causes a compile error. Cast first if you need it.
✕ Forgetting @Override
If you misspell the method or change the parameters, Java treats it as a new method instead of an override. The @Override annotation catches this.
✕ Confusing overloading with overriding
Changing the parameter list creates an overload (compile-time), not an override (run-time). The method signature must match exactly.

Polymorphism Summary

Concept Details
Definition One superclass reference, many subclass behaviors
Requirement Inheritance + method overriding
Compile time Checks declared (reference) type for method existence
Run time Dispatches to actual (object) type's override
Limitation Cannot call subclass-only methods via superclass ref
Key benefit Write code once, works for all subclasses

Question 1 of 5

Given:
Animal a = new Cat();
a.speak();

Which version of speak() is executed?

Question 2 of 5

If Dog has a method fetch() that Animal does not, what happens when you write:
Animal a = new Dog(); a.fetch();

Question 3 of 5

A method is defined as:
public void feed(Animal a) { ... }

Which of the following is a valid call?

Question 4 of 5

What is the key difference between method overloading and method overriding?

Question 5 of 5

What does this loop print (approximately)?