Constructor overloading lets you create multiple ways to make an object with different starting information. It helps you build objects flexibly.
0
0
Constructor overloading in Java
Introduction
When you want to create an object with different sets of starting values.
When some information is optional while creating an object.
When you want to provide simple and detailed ways to create objects.
When you want to avoid writing many different methods to set initial values.
When you want to make your code easier to read and use.
Syntax
Java
class ClassName { ClassName() { // no-argument constructor } ClassName(type1 param1) { // constructor with one parameter } ClassName(type1 param1, type2 param2) { // constructor with two parameters } }
Each constructor has the same name as the class.
Constructors differ by the number or types of parameters.
Examples
This class has two constructors: one sets width and height to zero, the other sets them to given values.
Java
class Box { int width, height; Box() { width = 0; height = 0; } Box(int w, int h) { width = w; height = h; } }
This class shows three ways to create a Person: no info, just name, or name and age.
Java
class Person { String name; int age; Person() { name = "Unknown"; age = 0; } Person(String n) { name = n; age = 0; } Person(String n, int a) { name = n; age = a; } }
Sample Program
This program creates three Car objects using different constructors and prints their details.
Java
public class Car { String model; int year; // No-argument constructor Car() { model = "Unknown"; year = 0; } // Constructor with one parameter Car(String m) { model = m; year = 0; } // Constructor with two parameters Car(String m, int y) { model = m; year = y; } void display() { System.out.println("Model: " + model + ", Year: " + year); } public static void main(String[] args) { Car car1 = new Car(); Car car2 = new Car("Toyota"); Car car3 = new Car("Honda", 2022); car1.display(); car2.display(); car3.display(); } }
OutputSuccess
Important Notes
Constructor overloading improves code readability and flexibility.
If you define any constructor, Java does not create a default no-argument constructor automatically.
Use the 'this' keyword inside constructors to call another constructor if needed.
Summary
Constructor overloading means having multiple constructors with different parameters.
It helps create objects in different ways depending on available information.
Each constructor must have a unique parameter list.