DEV Community

Cover image for Polymorphism - [Java OOP #5]
rachel
rachel

Posted on • Updated on

Polymorphism - [Java OOP #5]

Polymorphism refers to the ability of a method to have multiple implementations based on what object is passed to it. Polymorphism can be divided into two types: runtime and compile-time.

Runtime Polymorphism

Runtime polymorphism, also known as dynamic polymorphism, is achieved by method overriding. The concept of method overriding was introduced in the previous article of this OOP series.

Runtime polymorphism is resolved during runtime, in which the JVM decides which method to invoke. Take a look at the example below:

Polymorphism example
Polymorphism example

Here, "obj" is a reference variable of the Cat superclass, but it is pointing to the object of the Tiger subclass. Hence the makeSound() method of the Tiger class is called.

Compile Time Polymorphism

Compile time polymorphism, also known as static polymorphism, is acheived by method overloading. Method overloading is when different methods possess the same name but different parameters. This can be done by changing the number, data types and order of parameters.

Try and run the sample code below and observe the results. For better understanding, you can create your own methods and experiment with different paramters.

class Test {

    public static int sum(int x, int y) {
        return x + y;
    }

    public static int sum(int x, int y, int z) {
        return x + y + z;
    }

    public static double sum(double x, int y) {
        return x + y;
    }

    public static double sum(int x, double y) {
        return x + y;
    }
}

class Main {
    public static void main(String[] args) {
        // invokes the first sum() method
        System.out.println(Test.sum(1, 2)); 

        // invokes the second sum() method
        System.out.println(Test.sum(1, 2, 3));

        // invokes the third sum() method
        System.out.println(Test.sum(1.0, 2));

        // invokes the fourth sum() method
        System.out.println(Test.sum(1, 2.0));
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)