Java is Everywhere
--
Study Java for a better life and future…
1. Polymorphism
Java is an object-oriented language, and polymorphism is one of its features. There are two types of polymorphism in Java. One is compile-time polymorphism and the other is runtime polymorphism.
(1.1) Compile-time Polymorphism
Compile-time polymorphism can be achieved with method overloading and operator overloading. However, Java does not support operator overloading.
(1.1.1) Method Overloading: Multiple functions have the same name but with different parameters. Their parameters can contain different types and various numbers.
Example:
class summation{
// Method with 2 parameters
int sum (int a, int b){
return a+b;
}
// Method with the same name but 2 double parameters
double sum(double a, double b){
return a+b;
}
// Method with the same name but 3 parameters
int sum(int a, int b, int c){
return a+b+c;
}
}
(1.2) Runtime Polymorphism
Runtime Polymorphism or Dynamic Method Dispatch is a process where a function call is resolved at runtime rather than at compile-time. This type of polymorchism is achieved by Method Overriding.
(1.2.1) Method Overriding: In this process of Runtime Polymorphism, an overridden method is called by a reference variable of a superclass.
Example:
class BankAccount{
void getMoney(){
System.out.print('Get back the money from your account.');
return;
}
}
class TomBankAccount extends BankAccount{
void getMoney(){
System.out.print('Tom's Bank Account');
}
}
class TestPolymorphism{
public static void main(String[] args){
BankAccount a;
BankAccount b;
a = new BankAccount();
b = new TomBankAccount();
a.getMoney(); // runs the method in BankAccount class
b.getMoney(); // runs the method in TomBankAccount class
}
}