Overriding

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java. In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding. Following are the usages of Java Method Overriding.

  1. Method overriding is used to provide the specific implementation of a method which is already provided by its superclass.
  2. Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

  1. The method must have the same name as in the parent class
  2. The method must have the same parameter as in the parent class.
  3. There must be an IS-A relationship (inheritance).

Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use method overriding.


\begin{lstlisting}
/Java Program to demonstrate why we need method overriding
/...
...lling the method with child class instance
obj.run();
}
}
\end{lstlisting}

Problem is that I have to provide a specific implementation of run() method in subclass that is why we use method overriding.