- Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes.
- When a method in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.
- Method overriding is one of the way by which java achieve Run Time Polymorphism.
Usage of Java 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).
What Cannot Be Overridden?
Static Methods: You cannot override static methods; defining a same-named static method in a subclass is called "method hiding".
Final Methods: Methods declared with the final keyword cannot be overridden.
Private Methods: Since private methods are not inherited, they cannot be overridden.
Constructors: Constructors are unique to their own class and cannot be overridden.
class Animal {
protected void displayInfo() {
System.out.println("I am an animal.");
}
}
class Dog extends Animal {
public void displayInfo() {
System.out.println("I am a dog.");
}
}
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}