Categories: Core JAVATutorial

Compile Time Polymorphism in Java

Compile time polymorphism or static method dispatch is a process in which a call to an overloading method is resolved at compile time rather than at run time. In this process, we done overloading of methods is called through the reference variable of a class here no need to superclass. 

Method Overloading in Java:
If a class have multiple methods by same name but different parameters, it is known as Method Overloading.

If we have to perform only one operation, having the same name of the methods increases the readability of the program. Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as sum(int,int) for two parameters, and sum2(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs. So, we perform method overloading to figure out the program quickly.

Advantage of method overloading?

Method overloading increases the readability of the program.

Different ways to overload the method:
There are two ways to overload the method in java

  • By changing number of arguments
  • By changing the data type

1. Example of By changing number of arguments:

class Calculation{
  void sum(int a,int b)
  {
     System.out.println(a+b);
  }
  void sum(int a,int b,int c){
     System.out.println(a+b+c);
   }

  public static void main(String args[]){
  Calculation obj=new Calculation();
  obj.sum(10,10,10);
  obj.sum(20,20);

  }
}
output:
30
40

2. Example of By changing the data type:
In this example, we have created two overloaded methods that differs in data type. The first sum method receives two integer arguments and second sum method receives two double arguments.

class Calculation{
  void sum(int a,int b){
    System.out.println(a+b);
   }
  void sum(double a,double b){
    System.out.println(a+b);
  }

  public static void main(String args[]){
  Calculation obj=new Calculation();
  obj.sum(11.5,11.5);
  obj.sum(30,20);

  }
}

output:
23.0
50

Why Method Overloaing is not possible by changing the return type of method?

In java, method overloading is not possible by changing the return type of the method because there may occur ambiguity. Let’s see how ambiguity may occur:

class Calculation{
  int sum(int a,int b)
  {
    System.out.println(a+b);
  }
  double sum(int a,int b){
    System.out.println(a+b);
   }

  public static void main(String args[]){
  Calculation obj=new Calculation();
  int result=obj.sum(30,20); //Compile Time Error
  }
}

Method Overloading and TypePromotion:

One type is promoted to another implicitly if no matching datatype is found. Let’s understand the concept by the figure given below:

As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The short datatype can be promoted to int,long,float or double. The char datatype can be promoted to int,long,float or double and so on.

Example of Method Overloading with TypePromotion:

class Calculation{
  void sum(int a,long b){System.out.println(a+b);}
  void sum(int a,int b,int c){System.out.println(a+b+c);}

  public static void main(String args[]){
  Calculation obj=new Calculation();
  obj.sum(20,20);//now second int literal will be promoted to long
  obj.sum(20,20,20);

  }
}

Output:
40
60

Example of Method Overloading with TypePromotion if matching found:
If there are matching type arguments in the method, type promotion is not performed.

class Calculation{
  void sum(int a,int b){System.out.println("int arg method invoked");}
  void sum(long a,long b){System.out.println("long arg method invoked");}

  public static void main(String args[]){
  Calculation obj=new Calculation();
  obj.sum(20,20);//now int arg sum() method gets invoked
  }
}

Example of Method Overloading with TypePromotion in case ambiguity:
If there are no matching type arguments in the method, and each method promotes similar number of arguments, there will be ambiguity.

class Calculation{
  void sum(int a,long b){System.out.println("a method invoked");}
  void sum(long a,int b){System.out.println("b method invoked");}

  public static void main(String args[]){
  Calculation obj=new Calculation();
  obj.sum(20,20);//now ambiguity
  }
}

Output:

Compile Time Error

Using null to overload methods in Java [duplicate]:
The following code compiles and goes fine.

public class Main
{
    public void temp(Object o)
    {
        System.out.println("The method with the receiving parameter of type Object has been invoked.");
    }

    public void temp(String s)
    {
        System.out.println("The method with the receiving parameter of type String has been invoked.");
    }

    public void temp(int i)
    {
        System.out.println("The method with the receiving parameter of type int has been invoked.");
    }

    public static void main(String[] args)
    {
        Main main=new Main();
        main.temp(null);
    }
}

In this code, the method to be invoked is the one that accepts the parameter of type String
Output:

The method with the receiving parameter of type String has been invoked.

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
Where you pass null as argument for an overloaded method, the method chosen is the method with the most specialized type, so in this case: String is chosen rather than the most tolerant: Object.

Among Object/String/int the choice is clear for the compiler: you will get the String’s one cause an int cannot be null and so its corresponding method is not eligible to be called in this case.

But if you change int for Integer, compiler will be confuse because both methods taking String is as accurate as Integer’s one (orthogonal in hierarchy).

<<Previous <<   || Index ||   >>Next >>
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago