What is polymorphism, what is it for, and how is it used?
Polymorphism:
It is the concept of object oriented programming.The ability of different objects to respond, each in its own way, to identical messages is called polymorphism.
Polymorphism results from the fact that every class lives in its own namespace. The names assigned within a class definition don’t conflict with names assigned anywhere outside it. This is true both of the instance variables in an object’s data structure and of the object’s methods:
Just as the fields of a C structure are in a protected namespace, so are an object’s instance variables.
Method names are also protected. Unlike the names of C functions, method names aren’t global symbols. The name of a method in one class can’t conflict with method names in other classes; two very different classes can implement identically named methods.
Method names are part of an object’s interface. When a message is sent requesting that an object do something, the message names the method the object should perform. Because different objects can have methods with the same name, the meaning of a message must be understood relative to the particular object that receives the message. The same message sent to two different objects can invoke two distinct methods.
The main benefit of polymorphism is that it simplifies the programming interface. It permits conventions to be established that can be reused in class after class. Instead of inventing a new name for each new function you add to a program, the same names can be reused. The programming interface can be described as a set of abstract behaviors, quite apart from the classes that implement them.
Examples:
Example-1: Here is a simple example written in Python 2.x.
class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
def talk(self): # Abstract method, defined by convention only
raise NotImplementedError("Subclass must implement abstract method")
class Cat(Animal):
def talk(self):
return 'Meow!'
class Dog(Animal):
def talk(self):
return 'Woof! Woof!'
animals = [Cat('Missy'),
Dog('Lassie')]
for animal in animals:
print animal.name + ': ' + animal.talk()
Example-2: Polymorphism is implemented in Java using method overloading and method overriding concepts.
Let us Consider Car example for discussing the polymorphism. Take any brand like Ford, Honda, Toyota, BMW, Benz etc., Everything is of type Car.
But each have their own advanced features and more advanced technology involved in their move behavior.
Now let us create a basic type Car
Car.java
public class Car {
int price;
String name;
String color;
public void move(){
System.out.println("Basic Car move");
}
}
Let us implement the Ford Car example.
Ford extends the type Car to inherit all its members(properties and methods).
Ford.java
public class Ford extends Car{
public void move(){
System.out.println("Moving with V engine");
}
}
The above Ford class extends the Car class and also implements the move() method. Even though the move method is already available to Ford through the Inheritance, Ford still has implemented the method in its own way. This is called method overriding.
Honda.java
public class Honda extends Car{
public void move(){
System.out.println("Move with i-VTEC engine");
}
}
Just like Ford, Honda also extends the Car type and implemented the move method in its own way.
Method overriding is an important feature to enable the Polymorphism. Using Method overriding, the Sub types can change the way the methods work that are available through the inheritance.
PolymorphismExample.java
public class PolymorphismExample {
public static void main(String[] args) {
Car car = new Car();
Car f = new Ford();
Car h = new Honda();
car.move();
f.move();
h.move();
}
}
Polymorphism Example Output:
In the PolymorphismExample class main method, i have created three objects- Car, Ford and Honda. All the three objects are referred by the Car type.
Please note an important point here that A super class type can refer to a Sub class type of object but the vice-verse is not possible. The reason is that all the members of the super class are available to the subclass using inheritance and during the compile time, the compiler tries to evaluate if the reference type we are using has the method he is trying to access.
So, for the references car,f and h in the PolymorphismExample, the move method exists from Car type. So, the compiler passes the compilation process without any issues.
But when it comes to the run time execution, the virtual machine invokes the methods on the objects which are sub types. So, the method move() is invoked from their respective implementations.
So, all the objects are of type Car, but during the run time, the execution depends on the Object on which the invocation happens. This is called polymorphism.