Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable. Let's first understand the upcasting before Runtime Polymorphism. If the reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:


\begin{lstlisting}
class A{}
class B extends A{}
A a=new B();//upcasting
\end{lstlisting}

For upcasting, we can use the reference variable of class type or an interface type. For Example:


\begin{lstlisting}
interface I{}
class A{}
class B extends A implements I{}
\end{lstlisting}



Subsections