If subclass (child class) has the same method as declared in the parent class, it is known as method overriding.
Usage of Method Overriding
Method overriding is used to provide the specific implementation of a method which is already provided by its superclass. Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
The method must have the same name as in the parent class. The method must have the same parameter as in the parent class. There must be an IS-A relationship (inheritance).
Example of method overriding
class A{ public int a;
public int met1(){
return 5;
}
public void met2(){
System.out.println("I am method 2 of class A");
}
}
class B extends A{
@Override
public void met2(){
System.out.println("I am method 2 of class B");
}
public void met3(){
System.out.println("I am method 3 of class B");
}
}
public class MethodOverriding {
public static void main(String[] args) {
A a = new A();
a.met2();
B b = new B();
b.met3();
}
}
Output:
I am method 2 of class A I am method 3 of class B
Java method overriding is mostly used in Runtime Polymorphism. Return type must be same or covariant in method overriding.