MainMenu

Home Java Overview Maven Tutorials

Sunday 15 January 2017

Polymorphism in Java With example



For Video Tutorial : Move on Youtube Channel


Note : Select the playlist as per your need & move with number sequence


Polymorphism in Java With example


The word ‘polymorphism’ literally means ‘a state of having many shapes’ or ‘the capacity to take on different forms’.
Polymorphism in Java has two types: Compile time polymorphism (static binding) and Runtime polymorphism (dynamic binding). Method overloading is an example of static polymorphism, while method overriding is an example of dynamic polymorphism.

Any object which satisfies more than one IS-A relationship is polymorphic in nature.

Example of Static polymorphism


package package1;
class chandan
{
public int sum(int a, int b)
{
return a+b;
}
public int multiple(int a, int b, int c)
{
return a*b*c;
}
}
public class Csc_poly
{
public static void main(String args[])
{
chandan obj = new chandan();
System.out.println( "Your sum is:" +obj.sum(2,3));
System.out.println( "Your multiplication is:" +obj.multiple(2,3,5));
}
}
Output :
Your sum is:5
Your multiplication is:30

Example of Dynamic polymorphism: In below example Object "ob" work for both class's method


class chandan
{
public int sum(int a, int b)
{
return a+b;
}
}
class chandan1 extends chandan
{
public int sum(int a, int b)
{
return a*b;
}
}
public class Csc_poly
{
public static void main(String args[])
{
chandan ob = new chandan();
System.out.println("Your sum is : " +ob.sum(2, 5));
chandan obj = new chandan1();
System.out.println("your multiplication is : " +obj.sum(3, 4));
}
}
Output :
Your sum is : 7
your multiplication is : 12

Tags:What is polymorphism ?, Static and Dynamic polymorphism with example

No comments:

Post a Comment