Polymorphism (Java)
Polymorphism means 'many forms' — the ability to treat objects of different classes through a shared parent type, where each object responds in its own way. The right method runs based on the object's actual type at runtime.
Java
For example, you can store different Animal subclasses in one Animal variable, call speak() on each, and get the correct sound for each one. This lets you write flexible code that works with future subclasses too.
Polymorphism in Java relies on inheritance or interfaces and on method overriding.
Examples
Java
class Animal { String speak() { return "..."; } }
class Cat extends Animal { String speak() { return "meow"; } }
class Dog extends Animal { String speak() { return "woof"; } }
public class Main {
public static void main(String[] args) {
Animal[] zoo = { new Cat(), new Dog() };
for (Animal a : zoo) {
System.out.println(a.speak());
}
}
}Output:
meow
woof