No announcement
 

Polymorphism

Polymorphism is the ability of an object to take on several forms. If an object can pass more than one IS-A test, then the object can be considered as polymorphic. Polymorphism allows us to perform an action in different ways.

There are two type of polymorphism, namely, Compile time polymorphism and runtime polymorphism.

Compile time polymorphism

This type of polymorphism can be obtained through method overloading.

  • Method overloading: When there are several functions with the same name, but different parameters, then the functions are said to be overloaded.

Example:

MethodOverloadingDemo.java

package com.codingnous.tutorial;

public class MethodOverloadingDemo {

	public static void main(String[] args) {

		// Create class object.
		MethodOverloadingDemo obj = new MethodOverloadingDemo();

		// Invoke method with 2 arguments.
		System.out.println("Sum of 2 and 3 = " + obj.addition(2, 3));

		// Invoke method with 3 arguments.
		System.out.println("Sum of 2, 3 and 8 = " + obj.addition(2, 3, 8));
	}

	// Method for addition of two numbers
	public int addition(int num1, int num2) {
		return (num1 + num2);
	}

	// Method for addition of three numbers
	public int addition(int num1, int num2, int num3) {
		return (num1 + num2 + num3);
	}

}

Output
Sum of 2 and 3 = 5 Sum of 2, 3 and 8 = 13

Runtime polymorphism

Also known as Dynamic Method Dispatch, in this, a function call to the overridden method is resolved at runtime. This can be achieved by Method overriding, which occurs when a sub class redefines a super class method. Refer to previous section.