Table of contents
Introduction
- The word “polymorphism” means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form
- A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So the same person exhibits different behavior in different situations. This is called polymorphism. Polymorphism is considered one of the important features of Object-Oriented Programming
Types Of PolyMorphism
- Compile Time PolyMorphism---Method Overloading
- Run-Time Polymorphism---Method Overriding
Method Overriding
Suppose we have Cental Bank as the parent class
Suppose we have ICCI,HDFC,BANK OF BARODA as the child class of the central Bank
Assume we have atrtibutes such as cheqing ,saving, overdraft in the parent class that is the Central Bank
We inherit the parent class by the children ICCI,HDFC,BANK OF BARODA
We create an object of the children class in the main method
Now since we have inherited the methods cheqing and saving we can override the methods in the child class,But the problem here is everytime we are calling the methods from the parent class to be overridden using the children class refernce
Instead what we can do is:
We can use parent type references for child objects
So using the parent reference and by just changing the value of the parent reference we can override all the children methods
This is nothing but polymorphism that is one element in different forms
example:
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
fighter f= new fighter();
passenger p1=new passenger();
airport a= new airport();
a.permit(f);
a.permit(p1);
}
}
class plane{
public void takeoff(){
System.out.println("this is general class for planes");
}
public void runway(){
System.out.println("this is general class for runway");
}
}
class airport{
public void permit(plane p){
p.runway();
p.takeoff();
}
}
class fighter extends plane{
public void takeoff(){
System.out.println("this is medium takeoff");
}
public void runway(){
System.out.println("this is medium runway");
}
}
class passenger extends plane{
public void takeoff(){
System.out.println("this is long takeoff");
}
public void runway(){
System.out.println("this is long runway");
}
}