Polymorphism
- Keshari Abeysinghe

- Mar 24, 2020
- 2 min read
Updated: Nov 30, 2020
Polymorphism in Java occurs when there are one or more classes or objects related to each other by inheritance. In other words, it is the ability of an object to take many forms. Inheritance lets users inherit attributes and methods, and polymorphism uses these methods for performing different tasks.
Polymorphissm discussed with two topics.
method overloading
method overriding
Method overloading
If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.Method overloading increases the readability of the program.
There are two ways to overload the method in java
By changing number of arguments
Example
class Adder{
static int add(int a,int b){
return a+b;
}
static int add(int a,int b,int c){
return a+b+c;
}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(13,13));
System.out.println(Adder.add(13,13,13));
}
}Expected Output
22
332. By changing the data type Example
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}Expected output
22
24.9Method Overriding
Method Overriding is redefining a super class method in a sub class.Method overriding is used for runtime polymorphism (will be discussed in future).
Rules for Method Overriding
The method signature i.e. method name, parameter list and return type have to match exactly.
The overridden method can widen the accessibility but not narrow it, i.e. if it is private in the base class, the child class can make it public but not vice versa.
There must be an IS-A relationship (inheritance).
Example:
class Girl{
public void writeLetter(){
// writeLetter method
}
class Boy extends Girl{
public void readLetter(){
//readLetter method
}
}
Class run{
public static void main (String args[]){
Grl g =new Girl();
g.writeLetter();
// writeLetter method in class Girl will be executed
Boy b=new Boy();
b.readLetter();
//readLetter method in class Boy will be executed
}
} Static method cannot be overridden. It can be proved by runtime polymorphism,
It is because the static method is bound with class whereas instance method is bound with an object. Static belongs to the class area, and an instance belongs to the heap area.
Happy Coding!
Comments