ProgramGuru

Polymorphism

Polymorphism

A school program needs reliable data and clear rules. Polymorphism lets a common reference call behavior supplied by different objects. Overriding chooses an instance implementation at runtime; overloading selects among signatures using compile-time types.

  1. Understand

    Polymorphism lets a common reference call behavior supplied by different objects.

  2. Apply

    Trace the Java example, predict its output and explain the result before running it.

  3. Avoid mistakes

    Overloading and overriding are different mechanisms. The declared reference type limits which members can be called.

Polymorphism

In Java, polymorphism is one of the four core principles of object-oriented programming (OOP), alongside inheritance, encapsulation, and abstraction. At its core, polymorphism allows objects to take many forms depending on the context. This dynamic nature leads to more flexible and maintainable code.

There are two main types of polymorphism in Java:

  • Compile-time Polymorphism (also known as method overloading)
  • Runtime Polymorphism (also known as method overriding)

1. Compile-time Polymorphism (Method Overloading)

Compile-time polymorphism occurs when multiple methods in the same class have the same name but different parameter lists. The decision about which method to call is made by the compiler.

Example: Method Overloading

  public class Calculator {
    int add(int a, int b) {
        return a + b;
    }

    double add(double a, double b) {
        return a + b;
    }

    int add(int a, int b, int c) {
        return a + b + c;
    }
    
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println(calc.add(2, 3));
        System.out.println(calc.add(2.5, 3.5));
        System.out.println(calc.add(1, 2, 3));
    }
}
5
6.0
6

Explanation:

Here, the method add is overloaded three times. The compiler picks the correct version to invoke based on the number and types of arguments. This helps in writing intuitive APIs while avoiding redundant method names.

2. Runtime Polymorphism (Method Overriding)

Runtime polymorphism happens when a subclass provides a specific implementation of a method that is already defined in its superclass. The method that gets executed is determined at runtime based on the object's actual type.

Example: Method Overriding

  class Animal {
    void sound() {
        System.out.println("Some generic animal sound");
    }
}

class Dog extends Animal {
    void sound() {
        System.out.println("Dog barks");
    }
}

class Cat extends Animal {
    void sound() {
        System.out.println("Cat meows");
    }
}

public class TestPolymorphism {
    public static void main(String[] args) {
        Animal a;
        a = new Dog();
        a.sound();

        a = new Cat();
        a.sound();
    }
}
Dog barks
Cat meows

Explanation:

Even though the reference variable a is of type Animal, the actual object it points to is either a Dog or a Cat. At runtime, Java determines the real object and invokes the appropriate sound() method. This is known as dynamic method dispatch.

Polymorphism in Action: Real-World Analogy

Imagine you have a remote control. Whether it operates a TV, a fan, or an AC depends on the device it’s currently linked to. The same remote (reference) can behave differently (method call) depending on the actual device (object instance) — this is polymorphism in everyday life.

Benefits of Using Polymorphism

  • Extensibility: Add new classes without modifying existing code.
  • Maintainability: Simplifies managing and debugging.
  • Reusability: Write generic code that works with any subclass.

Things to Remember

  • Overloading is determined at compile time, based on method signatures.
  • Overriding is resolved at runtime, based on the actual object type.
  • Only instance methods can be overridden, not static methods.
  • Constructors cannot be overridden or overloaded in the same way.

Quick Recap

Feature Method Overloading Method Overriding
Type Compile-time Runtime
Class Involvement Same class Parent and child classes
Signature Different parameter list Same method signature
Polymorphism Static Dynamic

Conclusion

Java Polymorphism isn’t just a concept—it’s a paradigm shift in how we design programs. With method overloading, you get cleaner, more intuitive code. With method overriding, you get flexibility and adaptability.

Important boundaries and mistakes

Overloading and overriding are different mechanisms. The declared reference type limits which members can be called.

Try the school example

Before running this Java program, write down each line you expect to see. Identify the value, branch, object or exception responsible for each line. Then explain whether the following assumption is valid: Overloading and overriding are different mechanisms.

Java 17 · Main.java · complete practice program

public class Main  {
  static abstract class Person  {
    abstract String role();
  }
  static class Teacher extends Person  {
    @Override String role()  {
      return "Teacher";
    }
  }
  public static void main(String[] args)  {
    Person p = new Teacher();
    System.out.println(p.role());
  }
}

Worked answer and reasoning

Java 17 · Main.java · source repeated for this answer

public class Main  {
  static abstract class Person  {
    abstract String role();
  }
  static class Teacher extends Person  {
    @Override String role()  {
      return "Teacher";
    }
  }
  public static void main(String[] args)  {
    Person p = new Teacher();
    System.out.println(p.role());
  }
}

Expected output

Teacher

Polymorphism lets a common reference call behavior supplied by different objects. Overriding chooses an instance implementation at runtime; overloading selects among signatures using compile-time types.

Overloading and overriding are different mechanisms. The declared reference type limits which members can be called.

Run with javac Main.java, then java Main. The declaration inside Main keeps the helper type available to this standalone example.

Check your understanding

For the complete practice program in this lesson, which output is expected on Java 17?
Choose one answer. You can try again.

Answer and explanation

Teacher

Polymorphism lets a common reference call behavior supplied by different objects. Overriding chooses an instance implementation at runtime; overloading selects among signatures using compile-time types. Overloading and overriding are different mechanisms. The declared reference type limits which members can be called.

What to remember

Polymorphism lets a common reference call behavior supplied by different objects. Overriding chooses an instance implementation at runtime; overloading selects among signatures using compile-time types. Overloading and overriding are different mechanisms. The declared reference type limits which members can be called.

Related explanations: Java Variables, Java If Statement - Syntax and Examples, Java Class - Blueprint of Objects, Exceptions in Java Introduction.

Supporting documentation: Official Java learning guide and Java 17 language specification.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Encapsulation →