Constructor Overloading

Constructor overloading in Java allows a class to have more than one constructor with different parameter lists. This gives you the flexibility to initialize objects in different ways. Constructor overloading provides the benefit of:

  • Multiple Initialization Options: You can initialize an object in different ways depending on the data available.
  • Cleaner Code: Avoids redundant code by allowing various constructors instead of multiple set methods.

Constructor overloading works by defining multiple constructors within a class, each with a unique set of parameters. Java then selects the appropriate constructor based on the arguments passed when an object is created.

Output

In the above example:

  • Default Constructor: Car() initializes the model to "Unknown" and the year to 2020.
  • Parameterized Constructors:
    • Car(String model) initializes the model with a given value, and sets the year to 2020.
    • Car(String model, int year) allows both the model and year to be specified.