What is Polymorphism in Programming?
Defining more than one function with the same name in the same class is known as Polymorphism. There are two types of Polymorphism are available.
Static Polymorphism:
Defining more than one function with the same name but with different arguments in the same class is known as Static Polymorphism. The process of defining more than one function with the same name, but with different arguments, within the same class is known as function overloading or function overwriting.
Example program:
Class poly1
{
Void function1 ()
{
System .out .println (“inside function1 ()”));
}
Void function1 (int x)
{
System .out .println (“inside function1 (int X)”));
}
Void function1 (int x, int y)
{
System .out .println (“inside function1 (int X, int y)”));
}
Int function1 () \\ * it is not possible to define this function in this class because a similar
function already exists. Even though the return data type is different, the return data type of the functions is not considered in java *\\
Return;
{
Int function1 (Boolean flag)
{
System .out .println (“inside function1 (Boolean flag)”));
}
Public static void main (string args [ ])
{
Poly1 p = new poly190;
p. function1 (6, 7);
}
}
We are passing values 6 and 7 as arguments to function 1. So it is clear that void function1 (int x, int y) is going to receive these arguments and get executed. I.e. the function will be chosen depending on the arguments.
Disadvantages of Static Polymorphism:
With static polymorphism, there is a chance for the JVM to go into an ambiguous state which is completely undesirable. This is the disadvantage of Static Polymorphism.
Dynamic polymorphism:
Out of some functions with the same name, and the same arguments, the function which has to be executed is decided at runtime. This concept is known as dynamic polymorphism. Dynamic polymorphism is implemented using function overriding. Dynamic polymorphism can be achieved only through Inheritance. It is completely dependent upon inheritance.