Polymorphism translates from Greek as "many forms." In Object-Oriented Programming, it refers to the ability of different objects to be treated as instances of the same class through a common interface, while each object provides its own unique implementation.
There are two primary ways polymorphism is achieved in programming:
This occurs when multiple methods in the same class have the exact same name, but different parameters (different number of arguments or different types of arguments). The compiler decides which method to execute at compile time based on the arguments passed.
This is the true power of OOP. It occurs when a child class provides a specific implementation of a method that is already provided by its parent class.
Imagine an array of Animal objects. Some are Dog objects, some are Cat objects. You can write a loop that iterates through the array and calls .makeSound() on every animal. You don't need to check if the animal is a dog or a cat; polymorphism ensures that the Dog barks and the Cat meows automatically at runtime.
While classical inheritance allows code reuse, it creates rigid, tightly coupled hierarchies. An Interface offers a looser, purely behavioral form of polymorphism.
An Interface is a contract. It defines a list of empty methods without any implementation. Any class that "implements" the interface signs a contract promising to provide the actual code for all those methods.
Because many languages (like Java and C#) do not allow Multiple Inheritance (inheriting from two parent classes), interfaces solve the problem. A class can inherit from only one parent class, but it can implement infinite interfaces.
For example, a Smartphone class might inherit from ElectronicDevice, but it can also implement the Camera interface, the GPS interface, and the Phone interface.
Design Principle: "Program to an interface, not an implementation." This makes your code extremely flexible and decoupled, as you depend on abstract behaviors rather than rigid, concrete classes.