Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Compile Time Polymorphism in Java

Last Updated on March 21, 2023 by Prepbytes

The term polymorphism comes from two Greek words, poly means many and morphs means forms. It allows us to perform various operations by using the same method.
There are two types of polymorphism: Dynamic is referred to as Runtime polymorphism and Static as Compile time polymorphism

What is Compile Time Polymorphism in Java?

Early binding or static polymorphism are other names for compile time polymorphism in Java. Compile time polymorphism gets its name from the fact that the binding is done at the time of compilation. Connecting the function call and the function body is referred to as binding. It is accomplished via overloading operators and methods as well as by modifying the function’s signature. The class’s reference variable handles the overloading of methods. By adding additional features to an operator, operator overloading is accomplished. The return value and its type, as well as the parameters and their types, are referred to as the function’s signature. It outlines a function’s input and output.

Example of Compile Time Polymorphism in Java:

class SimpleCalculator
{
    int add(int a, int b)  // method 1- addition of two numbers
    {
     	return a+b;
    }
    int  add(int a, int b, int c)  // method 2- addition of three numbers
    {
     	return a+b+c;
    }
}
public class DemoCal
{
   public static void main(String args[])
   {	// making object named obj for reference
   	SimpleCalculator obj = new SimpleCalculator();
   	System.out.println(obj.add(10, 20));  // method 1 is called because 2 parameters
   	System.out.println(obj.add(10, 20, 30)); // method 2 is called because 3 parameters
   }
}

By altering the number of parameters in the argument, the methods are overloaded in this. The first add method takes two arguments (a and b), and it returns the sum of the two numbers added together. In contrast, the second add method takes three arguments (a, b, and c), and it returns the sum of the three numbers added together.

To sum it up:

  • By altering the arguments, the example’s primary method (add) is overloaded.
  • The first method returns the result of adding two numbers and requires two arguments.
  • The second approach returns the result of adding three digits.
  • An object for reference is generated in the main class.
  • This object is used to invoke the SimpleCalculator class’ add function.
  • The first add method is invoked if the user uses the add method and includes two arguments in the argument.
  • The second add method is called if the number of arguments passed is 3.

Advantages of Compile-Time Polymorphism in Java

Compile time polymorphism in Java has a number of benefits. The principal benefit of compile-time polymorphism is as follows:

  • Code debugging gets simpler
  • We can reuse the code because of that.
  • The code is bound during the compilation phase.
  • The operation of the code is made simpler and more effective by overloading the procedure.

Note: Connecting the function call and the function body is referred to as binding.

Method overloading in Java allows us to declare several methods in a class with the same function name as long as their argument declarations differ.
In order to distinguish between methods with similar names, the Java compiler looks at the method signature, which includes the method name, number of arguments, and type of parameters.

The difference can be:

  • There are several parameters.
  • sequence of the parameter orders
  • kinds of parameters for data

The Java compiler is helped by the variations in method signatures to bind the correct method. Method Overloading Guidelines are:

  • We can change the argument list (i.e number of parameter types, sequence).
  • We are able to alter the return type.
  • The access modifier is modifiable.
  • A method in the same class or subclass can be overloaded.

Syntax of Method Overloading:

void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }

The method overloaded, in this case, is func (). While the parameters are different, the methods have the same name.

Methods can be overloaded in a variety of ways. The many forms of method overloading include the following:

1. Overloading by Changing the Number of Parameters in the Argument

class MethodOverloading {
// overloading of method which takes single int object as a parameter
    private static void display(int a){
    	System.out.println("One Arguments: " + a);
    }
// method which takes two object or parameters
    private static void display(int a, int b){
    	System.out.println("Two Arguments: " + a + " and " + b);
    }
// main method
    public static void main(String[] args) {
    // calling display function by passing one parameter: method 1 is called
    	display(2);
// calling display function by passing two parameter: method 2 is called
    	display(2, 4);
    }
}

Output:

One Arguments: 2
Two Arguments: 2 and 4

In the prescriptive, it can be noticed that the display(int a) function is called for displaying one parameter whereas the display(int a, int b) method is internally invoked for displaying two arguments. The method name is the same as what is stated below, but the arguments or argument lists are kept separate.

2. By Changing Datatype of Parameter

class MethodOverloading {

    // this method accepts int datatype
    private static void display(int a){
    	System.out.println("Got Int data.");
    }

    // this method  accepts String object
    private static void display(String a){
    	System.out.println("Got String object.");
    }

    public static void main(String[] args) {
    	display(4);
    	display("PrepBytes");
    }
}

Output:

Got Int data.
Got String object.

In this case, the parameter’s data type is altered while the method name and the total number of parameters remain unchanged. Internally, the show(int a) function is used to display Int data, whereas the display(String a) method is used to display String data.

3. By Changing the Sequence of Parameters

class Student{
 
    // Method 1
    public void stuIdentity(String name, int id)
    {
 
    	// Printing name and id of student
    	System.out.println("stuName :" + name + " "
                       	+ "Id :" + id);
    }
 
    // Method 2
    public void stuIdentity(int id, String name)
    {
 
    	// Again printing name and id of person
    	System.out.println("Id :" + id + " "
                       	+ "stuName :" + name);
    }
}
 
// Class 2
// Main class
class PrepBytesMain {
 
    // Main driver method
    public static void main(String[] args)
    {
 
    	// Creating object of above class
    	Student stu= new Student();
 
    	// Passing name and id
    	// Note: Reversing order
   	stu.stuIdentity("Mohit", 1);
    	stu.stuIdentity(2, "shubham");
    }
}

The Student identification are shown in the example above. If the user passes in (name, id) as the arguments, Method 1 is executed; otherwise, if the user passes in (id, name), Method 2 is called internally.

Operator Overloading

Operator overloading is the practice of redefining an operator’s capabilities. It speaks about applying the same operation to several data kinds.
For instance, the concatenation of two strings ("a"+"b") results in "ab" when adding two numbers (1+3) when the "+" operator is used with strings.
Operator overloading is supported in programming languages like C++, however, it is not supported in Java.
Functions having unique names—the name of the operator to be overloaded—are examples of operator overloading. An overloaded operator has a list of parameters and a return type, just like any other function.
The table below displays the kind of object and the return type for each:

object return type
String+String String
Int+Int Int
String+Int String

Yet, the reason why Java does not enable operator overloading raises an issue.

Here are the following justifications for why Java does not enable operator overloading in order for you to comprehend this.

  • Operator overloading makes the code difficult. In this situation, both the compiler and the Java interpreter, or JVM, must put in extra work to determine the functionality of the operator used in the statement.
  • Programming mistake: This occurs because programmers become confused by the custom definition of operators, which raises the rate of error.
  • Developer-friendly IDE tools: Java makes it easy to create and integrate IDEs and environments without the need of operator overloading. However, operator overloading can be achieved in Java with the help of method overloading in a clear and error-free manner. For instance, operator overloading is used for contention of string type in Java. Note that you cannot define your own operator overloads.

Let’s take some examples for better understanding.

Example 1 to Concatenate Two Strings:

String concat = "one" + "two";

Output:

onetwo

Example 2 to Add Two Numbers:

int a=1, b=3;

Output:

a+b= 4

Consider a code snippet given below.

import java.util.Scanner;
public class OperatorOverloading {
    public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);

    	//Input the first string
    	System.out.println("Enter a string:");
    	String s1 = sc.next();

    	//Input the second string
    	System.out.println("Enter another string: ");
    	String s2 = sc.next();

    	//Plus operator concatenates the two Strings
    	System.out.println(s1+' '+s2);

    	//Input the first integer
    	System.out.println("Enter a number:");
    	int x = sc.nextInt();



    	//Input the second integer
    	System.out.println("Enter another number:");
    	int y = sc.nextInt();

    	//Plus operator adds the two numbers
    	System.out.println(x+y);
    }
}

Output:

Enter a string: Hello
Enter another string:
World
Hello World
Enter a number:
3
Enter another number:
5
8

When the "+" operator is used with an integer, the result is 4—the result of adding two integers. The "+" operator causes operator overload since it offers two distinct use cases when applied to various data types. Moreover, overloading operators for both int and floating points is done using operators like -, *, and /.

Summary

  • Early binding is used for Java compile-time polymorphism, commonly referred to as static polymorphism.
  • Early binding is the practice of resolving the method while the compiler is compiling an object and determining its type.
  • When two or more methods are declared with the same name as a class but different parameter declarations, this is known as method overloading.
  • Java’s polymorphism at compile time uses the specified type of reference to decide which method will be called at runtime.
  • It is utilized to add features, functionality, and behavior to Java programming.
  • Using the same operator on several data types is referred to as operator overloading.
  • For instance, adding two integers (1+3) yields the result "4", but concatenating two strings ("a"+"b") yields the result "ab" when the "+" operator is used with strings.
  • While method overloading can be used to accomplish operator overloading, Java does not allow it.

FAQs related to Compile Time Polymorphism in Java

1. What is the example of compile time polymorphism?
The technique in which the method is called compile time is referred to as compile-time polymorphism. Compile-time polymorphism is implemented using method overloading. Constructor Overloading and Method Hiding are two other instances of compile-time polymorphism.

2. Why it is called compile time polymorphism?
Early binding or static polymorphism are other names for compile-time polymorphism in Java. Compile-time polymorphism gets its name from the fact that the binding is done at the time of compilation.

3. What are the two types of polymorphism?
There are two forms of polymorphism in the Object-Oriented Programming (OOPS) language, which are as follows:
dynamic linking (or Compile time) Example of polymorphism: method overloading. Method overriding is an example of dynamic binding (or runtime) polymorphism.

4. What is overloading vs overriding?
When the method signatures of the superclass and the child class coincide, overriding takes place. When two or more methods in the same class have the same name but distinct parameters, this is known as overloading. Thank you for sharing your knowledge with the DigitalOcean Community.

5. What is compile time polymorphism and runtime polymorphism in python?
It is a concept that enables us to carry out a single job in a variety of methods. Run-time polymorphism and compile-time polymorphism are the two kinds of polymorphism. Method overloading is a run-time polymorphism example, while method overriding is a compile-time polymorphism example.

6. What is static vs runtime polymorphism?
Dynamic polymorphism is polymorphism that happens at runtime, while static polymorphism occurs at build time (during application execution). Early coupling is a feature of static polymorphism. Early binding resolves the precise function to execute at build time.

7. Can we overload main method?
In Java, the main() function can indeed be overloaded. Any number of main() methods can be overridden in a Java class. But the initial main() function, which is public static void main(String[] args), is what the JVM (Java Virtual Machine) looks for first.

Leave a Reply

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