A core concept of Object-Oriented Programming & Compile-Time Polymorphism
Method Overloading allows a class to have multiple methods with the same name but different parameter lists. It is an example of Compile-Time (or Static) Polymorphism.
Overloading by providing a different count of arguments in method definitions.
class Product {
// Multiplying two integer values
public int multiply(int a, int b) {
return a * b;
}
// Multiplying three integer values
public int multiply(int a, int b, int c) {
return a * b * c;
}
}
public class Main {
public static void main(String[] args) {
Product ob = new Product();
System.out.println("Product of 2 numbers: " + ob.multiply(1, 2));
System.out.println("Product of 3 numbers: " + ob.multiply(1, 2, 3));
}
}
Overloading by defining methods with different parameter data types.
class Product {
public int prod(int a, int b, int c) {
return a * b * c;
}
public double prod(double a, double b, double c) {
return a * b * c;
}
}
public class Main {
public static void main(String[] args) {
Product p = new Product();
System.out.println(p.prod(1, 2, 3)); // Calls int version
System.out.println(p.prod(1.0, 2.0, 3.0)); // Calls double version
}
}
Overloading by changing the sequence of parameter data types in the method declaration.
class Student {
public void studentId(String name, int rollNo) {
System.out.println("Name: " + name + ", Roll-No: " + rollNo);
}
public void studentId(int rollNo, String name) {
System.out.println("Roll-No: " + rollNo + ", Name: " + name);
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.studentId("Sweta", 1);
s.studentId(2, "Gudly");
}
}