![]() |
VOOZH | about |
Compile-time polymorphism also known as static polymorphism or early binding, is a type of polymorphism where the method call is resolved by the compiler during compilation. It allows multiple methods to have the same name but different parameter lists.
Compile-time polymorphism can be achieved through:
Method overloading is a feature that allows multiple methods in the same class to have the same name but different parameter lists. The compiler determines which method to call based on the number, type, or order of arguments.
Method overloading by changing the number of parameters
In this type, Method overloading is done by overloading methods in the function call with a varied number of parameters.
Syntax:
show(int a)
show(int a, int b)
number 1 : 3 number 1 : 4 number 2 : 5
Explanation: In the above example, we implement method overloading by changing several parameters. We have created two methods, show(int num1) and show(int num1, int num2). In the show(int num1) method display, one number and the void show(int num1, int num2) display two numbers.
Method overloading by changing Datatype of parameter
In this type, Method overloading is done by overloading methods in the function call with different types of parameters.
Syntax:
show(int a, int b)
show(double a, double b)
This is integer function This is double function
Explanation :The compiler calls the integer version when integer values are passed and the double version when double values are passed.
By changing thesequence of parameters
In this type, overloading is dependent on the sequence of the parameters.
Syntax:
show(int a, char b)
show(char a, int b)
integer : 6 and character : G character : G and integer : 7
Explanation: Although both methods have the same parameter types, their sequence differs. The compiler selects the method according to the order of arguments.
Changing only the return type of a method does not create a valid overloaded method because it causes ambiguity.
Invalid Syntax:
int sum(int a, int b)
String sum(int a, int b)
Operator overloading means giving multiple meanings to the same operator. Unlike C++, Java does not support user-defined operator overloading. However, similar behavior can be achieved using overloaded methods.
Syntax:
void add(int a, int b)
void add(String a, String b)
Addition of two integer :20 Concatenated strings :Operator overloading
Explanation: The same add() method name performs different tasks. One method adds integers, while the other concatenates strings, achieving behavior similar to operator overloading.