Method overriding in Java allows a subclass to provide a specific implementation of a method that is already defined in its parent class.
It is the core mechanism behind runtime polymorphism, to decide at runtime which method version to execute based on the actual object type.
Core Rules
Same method name.
Same no of Arguments- Argument must be same as the parent class method.
Same return type- Must be same as the parent method's return type.
Access Modifiers- The child class's method cannot be more restrictive than the parent's method (e.g., if the parent method is
public, the child method cannot be private orprotected)Inheritance- It can only be used on inherited methods.
Example Code
public class MSDhoni
{
public void giveCaptaincy(){
System.out.println("MSDhoni gives the Test Captaincy to Virat Kohli");
}
}
public class ViratKohli extends MSDhoni
{
public static void main(String[] args)
{
MSDhoni testcaptain = new MSDhoni();
testcaptain.giveCaptaincy();
ViratKohli testCaptain = new ViratKohli();
testCaptain.giveCaptaincy();
}
public void giveCaptaincy() {
System.out.println("Virat Kohli is the Test captain and Want Whiteball captaincy too.");
}
}

Top comments (0)