Runtime Polymorphism in java
Generally, polymorphism means the ability to appear in many forms. It’s refers to the ability of an object to take many forms. Polymorphism is needed when a parent class reference is used to refer a child class object
There are two types of polymorphism in Java, compile-time polymorphism and runtime polymorphism. We can perform polymorphism by method overloading and method overriding.
Runtime polymorphism:
Method overrding is runtime polymorphism. The name and parameter both have to be same. In method overriding the method is invoked at runtime.
it's executed at runtime since the compiler dosen't know which method is going to be excuted, wether the base class or the derived class method.
class Animal{
public void eat(){
print "animal eating";
}
}
class Dog extends Animal{
public void eat(){
print "dog eating";
}
}
Animal animal1 =new Animal();
animal1.eat(); // output: animal eating
Animal.animal2 = new Dog(); // it's called ****upcasting
animal2.eat(); // output: dog eating
Dog dog = new Animal(); //****Invalid (Reference variable can't point parent class)
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting.