Polymorphism - Method Overloading and Overriding in Java
"Poly" means multiple and "morphs" means forms. Hence polymorphism means multiple forms.
Polymorphism allows us to perform single action in different ways.
In Java it is classified into two parts:
- Static or compile-time polymorphism (Method Overloading)
- Dynamic or run-time polymorphism (Method Overriding)
1. Static or Compile-time polymorphism:
This type of polymorphism is achieved by using Method Overloading.
Method Overloading:
When we define multiple functions with same name but different parameters, then this is called method Overloading.
- function can be overloaded by
1. the number of parameters
2. the type of parameters
3. the order of parameters
- return type of overloaded functions could be of any possible type, hence we cannot overload methods with their return type
For Example:
public class Program{
public static void sayHello() {
System.out.println("Hello World!");
}
public static void sayHello(String name) {
System.out.println("Hello: " + name + " Welcome to our blog...");
}
public static void sayHello(String name, int repeat) {
for(int i=0; i<repeat-1; i++) {
System.out.println("Hello: " + name + " Welcome to our blog...");
}
}
public static void sayHello(String person1, String person2) {
System.out.println(person1 + " is saying Hello to " + person2);
}
public static void main(String[] args) {
sayHello(); //Line 1
sayHello("John"); //Line 2
sayHello("Joey", 3); //Line 3
sayHello("Joey", "Rachel"); //Line4
}
}
Output:
Hello World!
Hello: John Welcome to our blog...
Hello: Joey Welcome to our blog...
Joey is saying Hello to Rachel
Notice here at Line1 and Line2 are overloaded because number of arguments are different
while Line3 and Line4 are overloaded because types of arguments are different.
2. Dynamic or Run-time Polymorphism:
This type of polymorphism is achieved by method overriding where the function call to the overridden method is resolved during runtime.
Method Overriding:
When the derived class contains the definition of one of the methods of the base class. Here base class is called overridden method.
-function can be overridden by:
1. name of the method should be same
2. number of parameters should be same
3. types of parameters and return type should also be same
Note: While overriding the method the visibility of access modifier can be greater but not lower.
- use @Override annotation to mark an overridden method
For Example:
class Derived{
public void sayHello() {
System.out.println("Hello from Derived Class..");
}
}
public class Program extends Derived{
@Override
public void sayHello() {
System.out.println("Hello from Base/Program Class ");
}
public static void main(String[] args) {
Program p = new Program();
p.sayHello(); //Output: Hello from Base/Program Class
}
}
To learn more about inheritance, click here
Comments
Post a Comment