Java Program to demonstrate method Overloading.
Objective
Write a Java program to demonstrate Compile-Time Polymorphism (Method Overloading) by adding different data types.
Algorithm / Approach
- Create a class
Test. - Define a method
add(int a, int b)that calculates and prints the sum of two integers. - Define a second method with the exact same name
add(double a, double b)that calculates and prints the sum of two doubles. - In
main, instantiate theTestclass. - Call
add(4, 5)andadd(4.5, 7.8).
Test.java
class Test {
void add(int a, int b) {
int c = a+b;
System.out.println("Sum = "+c);
}
void add(double a, double b) {
double c = a+b;
System.out.print("Sum = "+c);
}
public static void main(String[] a)
{
Test t = new Test();
t.add(4,5);
t.add(4.5,7.8);
}
}
Expected Output
Sum = 9 Sum = 12.3
Explanation of the Program
- Polymorphism means "many forms". Method Overloading is a type of compile-time polymorphism.
- In Java, you can have multiple methods in the same class with the exact same name, as long as their parameter lists (number of arguments, or data types of arguments) are different.
- When you call
t.add(), the Java compiler looks at the arguments you passed in. If they are integers, it binds the call to the integer version of the method. If they are decimals, it binds to the double version.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)