oop Polymorphism Method Overriding


Example

Method overriding is the way of using polymorphism between classes. if one class is inherited from another, the former (sub class) can override the latter's (super class's) methods, and change the implementation.

this is used where the super class defines the more general implementation of the method while the sub class uses a more specific one.

Consider following example:

We have a class for Mammals:

class Mammal {
  void whoIam () {
    System.out.println("I am a Mammal");
  }
}

Then we have a class for Dog, which is a Mammal:

class Dog extends Mammal {
  @Override
  void whoIam () {
    super.whoIam();
    System.out.println("I am a Dog!");
  }
}

In this example, we define whoIam() method in Mammal class, where the mammal say it is a Mammal. But this is a general term, as there are a lot of Mammals out there. Then we can inherit Dog class from Mammal class, as Dog is a Mammal. But, to be more specific, Dog is a Dog as well as a Mammal. Hence, Dog should say, I am a Mammal and also I am a Dog. Hence we can Override the whoIam() method in super class (Mammal class, that is) from sub class (the Dog class).

We can also call the super class's method using super.whoIam() in Java. Then, the Dog will behave like a Dog, while also behaving like a Mammal.