Constructor Overloading - Abhijeet120303/SGTek-Internship GitHub Wiki

Constructor Overloading


  • Constructor overloading is a concept in object-oriented programming that allows a class to have multiple constructors with different parameter lists.
  • If a class contain multiple Constructor where each type of constructor have different parameter list is called constructor overloading.

Why Constructor Overloading?

  • Initialization Flexibility: Different scenarios may require different initializations. Constructor overloading allows developers to choose the most appropriate way to initialize an object based on specific needs.

  • Convenience: Constructor overloading makes it more convenient to create objects without manually setting each field after the object is created.

  • Readability: Multiple constructors with meaningful parameter names improve code readability. Each constructor can be named to reflect its purpose, making the code more self-explanatory.

  • Default Values: Constructors can provide default values for parameters, simplifying the creation of objects with default settings.

  • Code Reusability: Common initialization logic can be shared among different constructors, promoting code reusability.


Example


public class Customer {

	private int salary;

	private String name;

	public Customer() {
		this.name = "Abhijeet";
		this.salary = 100000;

	}

	public Customer(int salary, String name) {
		this.name = name;
		this.salary = salary;
	}

	public void display() {
		System.out.println(salary + " " + name);
	}

	public static void main(String[] args) {

		Customer c1 = new Customer();

		Customer c2 = new Customer(50000, "Gaurav");

		c1.display();
		
		c2.display();

	}

}