Polymorphism in Java

Filed Under: Java
Polymorphism In Java

Polymorphism is one of the core concepts of OOPS paradigm. The meaning of polymorphism is the condition of occurring in several different forms.

1. What is Polymorphism?

Polymorphism is the ability to perform different things in different scenarios. Sometimes, the polymorphism is based on the input parameters to the function. The polymorphism can be present in case of inheritance also. The functions behave differently based on the actual implementation.

2. Polymorphism Real Life Example

  • One of the functions of a Person is to write. If the person is presented with a pencil and paper, then he will write some words on it. If the person is presented with oil paint and a coloring book, he will make a painting. Here the function is behaving differently based on the input arguments.
  • A delivery person deliver items to the given address. If it’s a Postman, he will deliver letters and parcels to the home. If it’s a Pizza delivery person, he will deliver Pizza to you. Here the polymorphism in the delivery function is achieved through the different implementation.

3. Polymorphism in Java

Java supports polymorphism and it can be divided into two types.

  1. Compile Time Polymorphism
  2. Runtime Polymorphism

4. Compile Time Polymorphism

When the compiler is able to determine the actual function, it’s called compile-time polymorphism. There are two types of compile-time polymorphism.

  1. Method Overloading
  2. Operator Overloading

4.1) Method Overloading

When different functions in a class have the same name but different signature, it’s called method overloading. A method signature contains the name and method arguments. So, overloaded methods have different arguments. The arguments might differ in the numbers or the type of arguments. The method return type is not part of the signature.

Here is a simple example of method overloading in Java.


import java.io.File;

class Printer{
	
	void print(String message) {
		// printing string message
	}
	
	void print(String message, int count) {
		// printing message count times
	}
	
	boolean print(Object obj, File f) {
		//printing object to file
		return true;
	}
}

If you are looking for method overloading in JDK classes, you will find a lot of them in the String and primitive wrapper classes. For example, String valueOf() methods, Integer parseInt() methods, etc.

Method Overloading in Java

Method Overloading in Java String Class

4.2) Operator Overloading

Java doesn’t allow us to override operators. However, the addition (+) operator is overloaded for the String objects. When the addition operator is used with string objects, it concatenates them and returns a new string object.


jshell> 10 + 5
$1 ==> 15

jshell> 10.5 + 20.1
$2 ==> 30.6

jshell> "ABC" + "abc"
$3 ==> "ABCabc"

jshell> new Object() + new Object()
|  Error:
|  bad operand types for binary operator '+'
|    first type:  java.lang.Object
|    second type: java.lang.Object
|  new Object() + new Object()
|  ^-------------------------^

jshell> 
Recommended Read: String Concatenation in Java

5. Runtime Polymorphism

The runtime polymorphism is achieved by method overriding. When the superclass method is overridden in the subclass, it’s called method overriding.

In this case, the compiler is not able to determine whether the superclass or subclass method will get called. The method resolution happens at runtime based on the actual type of the object. That’s why it’s called runtime polymorphism. It’s also called Dynamic Method Dispatch.

Here is an example of runtime polymorphism in Java.


package com.journaldev.examples;

import java.util.Random;

public class DeliveryBoy {

	void deliver() {
		System.out.println("Delivering Item");
	}

	public static void main(String[] args) {
		DeliveryBoy db = getDeliveryBoy();
		db.deliver();
	}

	private static DeliveryBoy getDeliveryBoy() {
		Random rand = new Random();
		int num = rand.nextInt(10);
		return num % 2 == 0 ? new PizzaDeliveryBoy() : new Postman();
	}
}

class PizzaDeliveryBoy extends DeliveryBoy {

	@Override
	void deliver() {
		System.out.println("Delivering Pizza");
	}
}

class Postman extends DeliveryBoy {
	@Override
	void deliver() {
		System.out.println("Delivering Letters");
	}
}

The deliver() method is overridden in the PizzaDeliveryBoy and Postman classes. The compiler can’t determine whether the getDeliveryBoy() will return a PizzaDeliveryBoy or Postman. So, the method resolution happens at runtime.

If you run the program, the output will vary between “Delivering Letters” and “Delivering Pizza”.

6. Conclusion

The philosophy of Java has always been to take the best features of object-oriented programming. That’s why operator overloading feature was dropped in Java because it creates more confusion.

7. References

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages