Method overriding is when inherited, non-static methods can be changed in a child /subclass, to promote specialisation of the class. It supports Polymorphism, as the method called can change based on the type of object defined.
Specifically, if we have a parent superclass, and a subclass inheriting from it, and we have the same method signature, then the subclass method overrides the superclass method.
Method overriding can only occur in subclasses, i.e. is only possible through Inheritance
Method overriding cannot change the return type of the method
In Java
final
: Makes it impossible for subclasses to override a superclass method.
Example
Java
Let’s define a superclass Animal
and a subclass Rabbit
:
public class Animal {
protected int weight;
protected int stamina;
protected void Move() {
stamina -= weight;
}
}
public class Rabbit extends Animal {
...
}
We know that rabbits tend to burn their stamina faster than regular animals, so we could do:
public class Rabbit extends Animal {
@Override
protected void Move() {
stamina -= weight * 2;
}
}
Here, Rabbit.Move()
overrides Animal.Move()
if we create a Rabbit object, because they both share the same signature.