DEV Community

Mohan Mogi
Mohan Mogi

Posted on

Method Overriding

Method Overriding:

  • Method Overriding is an Object-Oriented Programming (OOP) concept.
  • Method overriding allows a child class to redefine a method of the parent class while keeping the same.
  • same method name.
  • same number of arguments
  • same return type in different classes(parent-child)
  • same access modifier.
  • It is used to achieve runtime polymorphism.

Rules for Method Overriding

  1. The method must have the same name as in the parent class.
  2. The method must have the same parameter list.
  3. The return type should be the same or compatible.
  4. Only inherited methods can be overridden.
  5. static, and private methods cannot be overridden.

Advantages

  1. Achieves runtime polymorphism.
  2. Allows a subclass to provide a specific implementation.
  3. Improves code flexibility and reusability.

Example code:

Parent Class

Child Class

Top comments (0)