Wednesday, July 7, 2021

Compile Time and Run Time Polymorphism | Method Overloading and Method Overriding

Polymorphism can be divide into poly + morphs which are greek words and means many forms. In Java, a concept via which we can perform the same job in different ways is known as polymorphism. It can be further divided into compile-time polymorphism and run-time polymorphism. Let us have a look at each of them:

1. Compile time polymorphism (Method Overloading):

Whenever the object is assigned the functionality at compile-time, it is known as compile-time polymorphism. It is achieved via Method overloading in java. Method overloading is a concept in which two methods of a class have the same signature but different parameters. For Example:

If we have a class called AutoPace, and we wanted to declare a method as 

public void study(String subject)

We can declare the "study" method only once with the argument as "String". But in case we need some additional functionality, say we need to pass the time duration for the study method as well, we can achieve it with method overloading by declaring another "study" method and changing the argument to: 

public void study(String subject, int duration)

The class will look something like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public class AutoPace{

	public static void study(String subject){
		System.out.println("Lets study: " + subject);
	}

	public static void study(String subject, int duration){
		System.out.println("Let's study : " + subject + " for next " + duration + " hours");
	}

	public static void main(String args[]){
		study("Java"); //Lets study: Java
		study("Java", 2); //"Let's study : Java for next 2 hours"
	}

}


Few more conecpts of Compile Time Polymorphis when dealing with int -> long -> float -> double:

Next, let us have a look at few method calls and try to understand their output:

Case 1:

Let's assume we have couple of methods in a class say:

1
2
3
4
5
6
7
public int sum(int i, int j){

	System.out.println("Integers arguments called")

	return i+j;

}

and, 

1
2
3
4
5
public long sum(long i, long j){
	System.out.println("Long arguments called")
	return i+j;
}

This is a case of polymorphism as the arguments are different for the method "sum". In this case, if we call method sum from the main class, something like: 

sum(1,2) -> Since the arguments are integers, the first method will be called and the output will be printed as "Integers arguments called".

Case 2:

Next, let us assume that only one method is available i.e.

1
2
3
4
5
6
7
public long sum(long i, long j){

	Systemout.println("long argument called");

	return i+j;

}

and let's make the same call as the first one i.e. sum(1,2) -> In this case, even if the passed parameters are (int,int) and the corresponding method is not available, it will pass on to the next method which will accept (long,long).

Note: The hierarchy followed in this case should be int -> long -> float -> double i.e. for any lower arguments passed as a parameter if the appropriate argument method is not available it will check for the higher-order argument.

Case 3:

Next, let's try to understand the behavior if we will try to write a couple of methods like:

1
2
3
4
5
6
7
8
public int sum(int i, int j){
  return i+j;
}


public long sum(int i, int j){
  return i+j;
}

In this case, the method name and parameters are the same, but the return type is different. But, this is not a valid scenario as the method signature is the same and the return type doesn't play any role in method overloading. Hence, it will throw an error.

Case 4: 

Next, let us try to understand the behavior if we will try to write a couple of methods like:

1
2
3
4
5
6
7
public int sum(int i, long j){
  return i+j;
}

public int sum(long i, int j){
  return i+j;
}

In this case, the method name is the same but the parameters are different as they are in a different order. One can argue that this is following method overloading, but since we are dealing with int and long type, this is an error. 

To understand it better, let us try to understand what happens if someone tries to call sum(1,2) from the main method. 

It will get confused between both the sum methods and will not be able to figure out which method to call and will throw an error stating that the method is ambiguous.


2. Run-Time Polymorphism (Run-Time Polymorphism):

Whenever the object is assigned the functionality at run-time, it is known as run-time polymorphism. It is achieved via Method overriding in java. Method overriding is a concept in which two methods can have the same signature but different definitions. It can be achieved by the use of the parent-child class relationship. For example:

If we have a class HatchBack with a method carSegment, something like:

1
2
3
4
5
public class HatchBack{
 public void carSegment(){
  System.out.println("This is a hatchback car")
 }
}

But let's suppose there is a child class known as Maruti that wants to extend the HatchBack class for its hatchback segments of cars. In this case, they can override the carSegment and update the definition of the method by:

1
2
3
4
5
6
public class Maruti extends HatchBack{
  @Override
  public void carSegment(){
    System.out.println("This is a maruti hatchback car.")
  }
}

In this case, the Maruti class has overridden the functionality of carSegment method and this polymorphism can be achieved at run-time as one can decide which object to instantiate during run-time. Complete implementation of Run-Time Polymorphism:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class HatchBack {
 
    public void carSegment()
    {
        System.out.println("This is a hatchback car");
    }
}
 
public class Maruti extends HatchBack {
 
    public void carSegment()
    {
        System.out.println("This is a maruti hatchback car.");
    }
 
    // Main Code
    public static void main(String args[])
    {
        HatchBack hatchBack = new Maruti();
        hatchBack.carSegment(); //This is a maruti hatchback car.
    }
}

0 comments:

Post a Comment

Contact Form

Name

Email *

Message *

Latest Post

Memory Management in JAVA

One of the most important features of Java is its memory management. Since Java uses automatic memory management, it becomes superior to tho...

Popular Posts