Monday, February 10, 2020

Polymorphism in Java

Polymorphism in Java

Polymorphism is a major concept of object-oriented programming. Poly means "multiple" and "morph" means forms. Polymorphism means that an object of a given class can have multiple forms, either in its own class or in any of its subclasses. In Java, the object of a derived/extended class can be used whenever the original class is required. This capability is known as polymorphism. Polymorphism promotes Java's “One interface-multiple method” approach.

For example, We have a class Calculator having method sum, now the sum is possible for integers, float, long or any other type of data. Whenever we use the method sum on class Calculator, this class in Java can have the capability to call the appropriate version of the method sum according to the input.
java polymorphism

Java is a programming language with a very strong object-oriented approach. Java provides complete and large support for polymorphism. We can discover polymorphism in Java with the following concepts,
  • Method overloading
  • Method overriding
  • Method hiding
  • Field hiding


Method overloading

In a Java class, methods with the same name but different signature inside a class is called method overloading.  Different versions of methods are targetted for different input data. In Method overloading, methods with the same name but a different signature are used within the same class. This type of polymorphism is also known as compile-time polymorphism. The Java compile-time environment can easily resolve which version of the method will be used for the given input.

Method overloading in Java
Method Overloading


For example, we can see method overloading in the program below,
example method overloading



A program to demonstrate Method Overloading

/***********Method OverLoading*************/
public class Sum {
public int add(int a, int b)
{
    return a+b;
}
public int add(int a, int b,int c)
{
    return a+b+c;
}
public float add(float a, float b)
{
    return a+b;
}
private float add(float a, float b,float c)
{
    return a+b;
}
public static void main(String[] args)
{
    Sum sum=new Sum();
    System.out.println(sum.add(5, 15));
    System.out.println(sum.add(12.3f, 19.4f));
    System.out.println(sum.add(9, 10,12));
    System.out.println(sum.add(10.4f, 2.4f,8.9f));
}
}

Output:
20
31.7
31

12.799999

Video Tutorial