Constructor chaining in java, please explain with examples, including its function, usage, etc.
Constructor chaining in Java is a technique where one constructor calls another constructor in the same class or in a superclass. This allows for code reuse and can help to avoid redundancy when initializing objects. Constructor chaining can be achieved using the this()
keyword to call another constructor in the same class or the super()
keyword to call a constructor from the superclass.
this()
to call another constructor in the same class.super()
to call a constructor from the superclass.Here’s an example that demonstrates both types of constructor chaining:
class Animal {
String name;
int age;
// Constructor of the superclass
public Animal(String name) {
this.name = name;
this.age = 0; // Default age
System.out.println("Animal constructor called: " + name);
}
public Animal(String name, int age) {
this.name = name;
this.age = age;
System.out.println("Animal constructor called: " + name + ", Age: " + age);
}
}
class Dog extends Animal {
String breed;
// Constructor of the subclass
public Dog(String name, String breed) {
super(name); // Calling the superclass constructor
this.breed = breed;
System.out.println("Dog constructor called: " + name + ", Breed: " + breed);
}
public Dog(String name, int age, String breed) {
super(name, age); // Calling the overloaded superclass constructor
this.breed = breed;
System.out.println("Dog constructor called: " + name + ", Age: " + age + ", Breed: " + breed);
}
}
public class Main {
public static void main(String[] args) {
Dog dog1 = new Dog("Buddy", "Golden Retriever");
Dog dog2 = new Dog("Max", 5, "Bulldog");
}
}
Animal Class:
System.out.println
statements in the constructors help to show when each constructor is called.Dog Class:
Dog
class extends the Animal
class.Animal
constructor that initializes the name and sets the age to 0.Animal
constructor that initializes both name and age.Main Class:
main
method, two Dog
objects are created, demonstrating how constructor chaining works. The output will show the order in which the constructors are called.When you run the above code, you will see output similar to this:
Animal constructor called: Buddy
Dog constructor called: Buddy, Breed: Golden Retriever
Animal constructor called: Max, Age: 5
Dog constructor called: Max, Age: 5, Breed: Bulldog
This output illustrates how the constructors are chained together, showing the flow of control from the subclass to the superclass constructors.
Constructor chaining is a powerful feature in Java that promotes code reuse and helps in organizing initialization logic. By using this()
and super()
, you can create more maintainable and understandable code.