← Back to Chapters

Java Polymorphism

? Java Polymorphism

? Quick Overview

Polymorphism is one of the core principles of Object-Oriented Programming in Java. It allows a single method or object to behave differently based on the context. The word polymorphism means many forms.

? Key Concepts

  • Same method name, different behavior
  • Achieved using inheritance and method overriding
  • Improves flexibility and scalability
  • Supports runtime decision making

? Syntax / Theory

Java supports two types of polymorphism:

  • Compile-time Polymorphism (Method Overloading)
  • Runtime Polymorphism (Method Overriding)

? Code Example (Runtime Polymorphism)

? View Code Example
// Parent class
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

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

// Main class demonstrating polymorphism
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
}
}

? Live Output / Explanation

Output:

Dog barks

Although the reference type is Animal, the overridden method of Dog is called at runtime. This is runtime polymorphism.

? Interactive Simulation

Change the object type below to see how the same line of code executes different logic at runtime.

Animal myPet = new Animal(); myPet.sound(); // Calling the same method
> Waiting for execution...

? Tips & Best Practices

  • Always use method overriding with inheritance
  • Use @Override annotation for clarity
  • Prefer polymorphism over multiple condition checks
  • Parent reference can hold child object

? Try It Yourself

  • Create a base class Shape with method draw()
  • Override draw() in Circle and Rectangle
  • Call methods using base class reference