In Java, constructor overloading refers to the practice of defining multiple constructors within a class, each with a different parameter list. This allows an object to be instantiated in various ways, providing flexibility and versatility in how instances of a class are created. Constructor overloading is a form of polymorphism in which a class has multiple constructors with different parameter signatures.
Constructor overloading is a powerful feature in Java that enables a class to have multiple constructors with different parameter lists. This allows developers to create objects in different ways based on the specific needs of the application. Each constructor within the class provides a unique way to initialize the object, catering to various scenarios and requirements.
The key to constructor overloading is the ability to define constructors with different parameter types, order, or number of parameters. When an object is created, the appropriate constructor is called based on the arguments provided during instantiation.
Here’s an example that demonstrates how constructors overloaded
class Sparrow { private String name; private int age; private String color; public Sparrow() { this.name = "Default Sparrow"; this.age = 1; this.color = "Brown"; } public Sparrow(String name) { this.name = name; this.age = 1; this.color = "Brown"; } public Sparrow(String name, int age) { this.name = name; this.age = age; this.color = "Brown"; } public Sparrow(String name, int age, String color) { this.name = name; this.age = age; this.color = color; } public Sparrow(Sparrow other) { this.name = other.name; this.age = other.age; this.color = other.color; } public void displayDetails() { System.out.println("Name: " + name); System.out.println("Age: " + age + " years"); System.out.println("Color: " + color); System.out.println(); } } public class ConOverloadDemo{ public static void main(String[] args) { Sparrow defaultSparrow = new Sparrow(); Sparrow namedSparrow = new Sparrow("Chirpy"); Sparrow customSparrow = new Sparrow("Tweetie", 2, "Yellow"); Sparrow copiedSparrow = new Sparrow(customSparrow); System.out.println("Default Sparrow:"); defaultSparrow.displayDetails(); System.out.println("Named Sparrow:"); namedSparrow.displayDetails(); System.out.println("Custom Sparrow:"); customSparrow.displayDetails(); System.out.println("Copied Sparrow:"); copiedSparrow.displayDetails(); } }
Output:
D:\>java ConstructorOverloadingDemo
Default Sparrow:
Name: Default Sparrow
Age: 1 years
Color: Brown
Named Sparrow:
Name: Chirpy
Age: 1 years
Color: Brown
Custom Sparrow:
Name: Tweetie
Age: 2 years
Color: Yellow
Copied Sparrow:
Name: Tweetie
Age: 2 years
Color: Yellow
Code language: PHP (php)