Tuesday, March 31, 2020

Polymorphism in Java-Part 1



The concept by which we can perform a single action in different ways is polymorphism. It means that polymorphism allows you to define one interface and have multiple implementations.  Polymorphism can be performed in java by method overloading and method overriding.
The two types of polymorphism in Java are:
  1. Compile-time polymorphism
  2. Run-time polymorphism
Compile time polymorphism
It is also called as static polymorphism. Function overloading or operator overloading is used to achieve this type of polymorphism.
Method Overloading: Multiple functions having same name, but different parameters then are said to be overloaded. These functions can be overloaded by change in number of arguments or change in type of arguments.
//Java program for Method overloading
  
class MultiplyFun {
  
    // Method with 2 parameter
    static int Multiply(int a, int b)
    {
        return a * b;
    }
  
    // 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.6
Runtime Polymorphism

It is also called as Dynamic Method Dispatch. In this process the function call to the overridden method is resolved at runtime. Method overriding is used to achieve this type of polymorphism.

// Java program for Method overriding
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();
    }
}
Output: subclass1
subclass2

Rishita Jaiswal
K-28


13 comments: