Learning Java from 0 to Senior 6/100: Polymorphism in Java
2 min readOct 19, 2023
Polymorphism in Java — Flexibility in Object Interaction
Introduction to Polymorphism
Polymorphism, a Greek word meaning “many shapes,” is a crucial concept in object-oriented programming. It allows objects to be treated as instances of their parent class, enabling one interface to control access to a general class of actions.
Types of Polymorphism
In Java, polymorphism manifests primarily in two ways:
- Compile-time Polymorphism (Static Binding or Method Overloading): This occurs when multiple methods have the same name but different parameters (type, number, or both).
class Display {
public void show(int i) {
System.out.println("Displaying an integer: " + i);
}
public void show(String s) {
System.out.println("Displaying a string: " + s);
}
}
- Runtime Polymorphism (Dynamic Binding or Method Overriding): This occurs when a child class overrides a method from its parent class, allowing the invocation of a method implementation specific to the child class type.
class Animal {
public void sound() {
System.out.println("This is the animal sound");
}
}
class Dog extends Animal {
@Override…