Java overloading
Created By: chatGPT
In Java, overloading refers to the ability to create multiple methods with the same name but with different parameters. This allows methods to handle different kinds of data or inputs in a more intuitive way. Overloading can be done in two ways: method overloading and constructor overloading.
class OverloadExample {
// Method with two int parameters
int add(int a, int b) {
return a + b;
}
// Method with three int parameters
int add(int a, int b, int c) {
return a + b + c;
}
// Method with double parameters
double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
OverloadExample example = new OverloadExample();
System.out.println(example.add(5, 10)); // Calls the first method
System.out.println(example.add(5, 10, 15)); // Calls the second method
System.out.println(example.add(5.5, 10.1)); // Calls the third method
}
}
In the above example, the
add
method is overloaded with different parameter types and counts. When called, Java determines which method to execute based on the argument list provided. This increases programmability and keeps the code readable and manageable.class ConstructorExample {
// Constructor with one parameter
ConstructorExample(int a) {
System.out.println("Constructor with one parameter: " + a);
}
// Constructor with two parameters
ConstructorExample(int a, int b) {
System.out.println("Constructor with two parameters: " + a + ", " + b);
}
}
public class Main {
public static void main(String[] args) {
ConstructorExample obj1 = new ConstructorExample(10);
ConstructorExample obj2 = new ConstructorExample(10, 20);
}
}
In constructor overloading, you can have multiple constructors in a class that differ in the number of parameters or the type of parameters. In the example above, we have two constructors for
ConstructorExample
, illustrating how to create objects with varying parameters. This feature enables more versatile object creation in Java.class Area {
// Overloaded methods for calculating area
double calculateArea(double radius) {
return Math.PI * radius * radius;
}
double calculateArea(double length, double width) {
return length * width;
}
}
public class Main {
public static void main(String[] args) {
Area area = new Area();
System.out.println("Area of circle: " + area.calculateArea(5)); // Calls first method
System.out.println("Area of rectangle: " + area.calculateArea(5, 10)); // Calls second method
}
}