Polymorphism in Java

Polymorphism in Java

Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance.

There are two types of polymorphism in Java:

  • compile-time polymorphism

  • runtime polymorphism

We can perform polymorphism in java by method overloading and method overriding.

1. Compile time polymorphism

  • Compile-time polymorphism is also called static polymorphism

  • It is achieved through method overloading

In method overloading the methods have

  • same name

  • same class

  • different arguments (number/sequence/type)

Example of compile time polymorphism with a difference in the number of arguments:

class Test
{
    void show(int a,int b)
    {
        System.out.println("1");
    }
    void show(int a)
    {
        System.out.println("2");
    }
    public static void main(String[] args)
    {
        Test t=new Test();
        t.show(10,20);
        t.show(10);
    }
}

Example of compile time polymorphism with a difference in the sequence of arguments:

class Test
{
    void show(int a,String b)
    {
        System.out.println("1");
    }
    void show(String a,int b)
    {
        System.out.println("2");
    }
    public static void main(String[] args)
    {
        Test t=new Test();
        t.show(10,"abc");
        t.show("abc",10);
    }
}

Example of compile time polymorphism with a difference in the type of arguments:

class Test
{
    void show(int a)
    {
        System.out.println("1");
    }
    void show(String a)
    {
        System.out.println("2");
    }
    public static void main(String[] args)
    {
        Test t=new Test();
        t.show(10);
        t.show("abc");
    }
}

2. Run time polymorphism

  • Run-time polymorphism is also called dynamic polymorphism

  • It is achieved through method overriding.

In method overring the methods have

  • same name

  • different class

  • same arguments (number/sequence/type)

  • Inheritance between classes.

Example of compile time polymorphism:

class Test
{
    void show(int a, String b)
    {
        System.out.println("1");
    }
}
class X extends Test
{
    void show(int a,String b)
    {
        System.out.println("2");
    }
    public static void main(String[] args)
    {
        Test t=new Test();
        t.show(10,"abc");
        X x=new X();
        x.show(5,"abc");
    }
}