Polymorphism

Definition of Polymorphism:

Defining the more than one functionality with the same name in the same class is known as Polymorphism. There are two types of Polymorphism are available.

Static Polymorphism:

Defining the more than one functionality 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 functions 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, 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 the function1. 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 upon the arguments.

Disadvantages of Static Polymorphism:

With the 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, same arguments, the function which has to be executed is decided at the run time. 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.

Polymorphism Homework Help