About Lesson
Also called static polymorphism. It is type of polymorphism that is resolved during compilation process. It is done through function/method overloading.
At compile time, Java compiler determines which method to call depending on the arguments count/type passed in the method call.
Method Overloading: In this, a class have more than one method with the same name and different parameters. Parameters differs in:
- Number of parameters, and/or
- Type of parameters
Method’s return type and access modifiers does not play a role in method overloading. Overloading is determined by the method signature (name and parameter list).
public class MathOperations {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}
// Method to add three integers
public int add(int a, int b, int c) {
return a + b + c;
}
// Method to add two double values
public double add(double a, double b) {
return a + b;
}
// Method to add an integer and a double
public double add(int a, double b) {
return a + b;
}
// Method to add a double and an integer
public double add(double a, int b) {
return a + b;
}
}
public class CompileTimePolymorphism {
public static void main(String[] args) {
MathOperations math = new MathOperations();
// Call the overloaded add methods
System.out.println("Addition of two integers: " + math.add(5, 10)); // Output: 15
System.out.println("Addition of three integers: " + math.add(5, 10, 15)); // Output: 30
System.out.println("Addition of two doubles: " + math.add(5.5, 10.5)); // Output: 16.0
System.out.println("Addition of an integer and a double: " + math.add(5, 10.5)); // Output: 15.5
System.out.println("Addition of a double and an integer: " + math.add(5.5, 10)); // Output: 15.5
}
}