Polymorphism is a key component of Java’s Object Oriented Nature. There are two types of polymorphism we will discuss. Compile Time Polymorphism(Static Polymorphism) and Runtime Polymorphism (Dynamic Polymorphism) .
What is Compile Time Polymorphism? – This exists with method overloading. For example a call to a overloaded method would be resolved during compile time instead of runtime.
public class AddSomething {
// adds two numbers
public int addNumbers(int a, int b){
return a + b;
}
// adds three numbers
public int addNumbers(int a, int b, int c){
return a + b + c;
}
// adds four numbers
public int addNumbers(int a, int b, int c, int d){
return a + b + c + d;
}
}
public class AddSomethingTest{
public static void main(String args[]){
AddSomething add = new AddSomething();
add.addNumbers(3,4,7);
}
}
Line 22 – Is where the compiler is determining what method to call within the AddSomething class. This is a lot quicker to have this figured out at compile time instead of runtime. Helps with the performance of your application.
What is Runtime Polymorphism? This occurs with method overriding via inheritance or implementing an interface. Please check out the example below.
public class Animal {
public void eat() {
System.out.println("I have a generic way of eating");
}
}
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("I eat like a dog");
}
}
public class Pig extends Animal {
@Override
public void eat() {
System.out.println("I eat like a pig");
}
}
public class RuntimePolymorphismTest {
public static void main(String args[]){
Animal a1 = new Dog();
Animal a2 = new Pig();
System.out.println(a1.eat());
System.out.println(s2.eat());
}
}
On lines 30-31, we create Animal (Parent / Super class) reference variables. Where one points to a Dog object and the other a Pig object. Lines 32-33 is where the Runtime Polymorphism is happening. In this case the eat methods of the Dog and Pig class are called and not that super class (parent) of the two.