Polymorphism is the ability to print output in one or more
forms.it performs single action in different ways.
It will be useful in application where one interface multiple
usage.
Polymorphism is divided into two types:
Compile type polymorphism and run time polymorphism
Compile type polymorphism:it also known static polymorphism,
This type of polymorphism is used in function overloading and
operator overloading.
Example: void function (int a)
Void function (int a, int b)
Void function (int c)
When there are multiple functions with different parameters
-
- Example: By using different types of arguments
// Java program for Method overloading
class MultiplyFun {
// Method with 2
parameter
static
int Multiply( int
a, int b)
{
return
a * b;
}
// Method with the
same name but 2 double parameter
static
double Multiply( double
a, double b)
{
return
a * b;
}
}
class Main {
public
static void main(String[]
args)
{
System.out.println(MultiplyFun.Multiply( 2 ,
4 ));
System.out.println(MultiplyFun.Multiply( 5.5 ,
6.3 ));
}
}
|
Output:
8
34.65
- Example: By using different numbers of
arguments
// Java program for Method overloading
class MultiplyFun {
// Method with 2
parameter
static
int Multiply( int
a, int b)
{
return
a * b;
}
// Method with the
same name but 3 parameter
static
int Multiply( int
a, int b, int
c)
{
return
a * b * c;
}
}
class Main {
public
static void main(String[]
args)
{
System.out.println(MultiplyFun.Multiply( 2 ,
4 ));
}
}
-
-
- Runtime polymorphism: It is also known as
Dynamic Method Dispatch. It is a process in which a function call
to the overridden method is resolved at Runtime. This type of
polymorphism is achieved by Method Overriding.
- Method overriding, on the other hand, occurs
when a derived class has a definition for one of the member
functions of the base class. That base function is said to be
overridden.
Example:
// Java program for Method overridding
class Parent {
void
Print()
{
System.out.println( "parent
class" );
}
}
class subclass1 extends
Parent {
void
Print()
{
System.out.println( "subclass1" );
}
}
class subclass2 extends
Parent {
void
Print()
{
System.out.println( "subclass2" );
}
}
class TestPolymorphism3 {
public
static void main(String[]
args)
{
Parent
a;
a
= new subclass1();
a.Print();
a
= new subclass2();
a.Print();
|
|
|
|