Java-Overloading
Overloading
- Overloading is a rule where multiple methods and constructors with the same name are defined together within the class.
- Overloading is of two types: Constructor and Method overloading
Java-Constructor Overloading
- Constructor overloading is the concept in which a class has multiple constructors with the same name but are different in terms of parameters and data type of parameters.
- It enables you to create objects with different initializations based on the given parameters.
Example:
package quipoHouse;
class Person {
private String name;
private int age;
public Person(String name) {
this.name = name;
this.age = 0;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Person person1 = new Person("Alice");
Person person2 = new Person("Bob", 30);
person1.displayInfo();
person2.displayInfo();
}
}
Output:
Name: Alice
Age: 0
Name: Bob
Age: 30
Java-Method Overloading
- Method overloading is the concept in which a class has multiple methods with the same name but are different in terms of parameters and data type of parameters.
- It optimizes the readability of the program.
- Method overloading is similar to constructor overloading, but it applies to methods.
Different ways to overload the methods:
1. Method overloading with differences in the number of parameters:-
Example:
package quipoHouse;
public class Overloading {
static int add(int a, int b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
System.out.println("Method Overloading With different no of parameters :" + Overloading.add(12, 13));
System.out.println("Method Overloading With different no of parameters :" + Overloading.add(12, 13, 14));
}
}
Output:
Method Overloading With different no of parameters : 25
Method Overloading With different no of parameters : 39
2. Method overloading with a difference in the data type of parameter:-
Example:
package quipoHouse;
public class Overloading {
static int add(int a, int b) {
return a + b;
}
static int add(double a, double b) {
return (int) (a + b);
}
public static void main(String[] args) {
System.out.println("Method Overloading With integer data type:" + Overloading.add(12, 13));
System.out.println("Method Overloading With double data type:" + Overloading.add(12.6, 13.5));
}
}
Output:
Method Overloading With integer data type: 25
Method Overloading With double data type:25