Junior — Middle
What is the purpose of constructor overloading in programming?
sobes.tech AI
Answer from AI
Constructor overloading is used to create multiple initialization options for an object with different sets of parameters. This allows creating objects with different states using the same class but different constructors, which increases flexibility and ease of use of the class.
Example in Java:
public class Person {
private String name;
private int age;
public Person() {
this.name = "Unknown";
this.age = 0;
}
public Person(String name) {
this.name = name;
this.age = 0;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
Here, you can create a Person object with different parameters using the appropriate constructor.