What is polymorphism?
- Polymorphism allows one method to perform different actions based on the object.
What is method overriding?
- Method overriding in the child class gives its own implementation of the method that already exists in the parent class.
why use
To achieve runtime polymorphism.
To change the parent class behaviour.
Rules
Method and parameters must have the same name.
static, final and private cannot be overridden.
Access modifiers cannot be weaker.
//parent class
public class MethodOverriding{
protected void display(){
System.out.println("Hello..");
}
}
//child class
public class Overriding extends MethodOverriding{
public void display(){
System.out.println("Hii..."); //child class overrides the parent class method.
}
public static void main(String[] args){
MethodOverriding m1=new Overriding();
m1.display();
}
}
D/B method overriding and Runtime polymorphism :
MO- child class changes parent class method.
RTP- JVM decides which method to call at runtime.
Top comments (0)