Constructor chaining java, explain and give code demonstration
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 helps to avoid duplication. 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()
.super()
.this()
and super()
are used, super()
must be called first, and it can only be called in the first line of the constructor.Here’s a simple example demonstrating constructor chaining in Java:
class Animal {
String name;
// Superclass constructor
Animal(String name) {
this.name = name;
System.out.println("Animal constructor called: " + name);
}
}
class Dog extends Animal {
String breed;
// Subclass constructor that calls the superclass constructor
Dog(String name, String breed) {
super(name); // Call to superclass constructor
this.breed = breed;
System.out.println("Dog constructor called: " + name + ", Breed: " + breed);
}
// Another constructor in the subclass that uses constructor chaining
Dog(String name) {
this(name, "Unknown Breed"); // Call to another constructor in the same class
}
}
public class Main {
public static void main(String[] args) {
Dog dog1 = new Dog("Buddy", "Golden Retriever");
System.out.println();
Dog dog2 = new Dog("Max");
}
}
String
parameter for the animal's name.Animal
. It has two constructors:
name
and breed
parameters. It calls the superclass constructor using super(name)
to initialize the name
field.name
parameter and uses constructor chaining to call the first constructor with a default breed of "Unknown Breed".main
method, two Dog
objects are created. The first one provides both name and breed, while the second one only provides the name, demonstrating how constructor chaining works.When you run the above code, the output will be:
Animal constructor called: Buddy
Dog constructor called: Buddy, Breed: Golden Retriever
Animal constructor called: Max
Dog constructor called: Max, Breed: Unknown Breed
This output shows that the constructors are called in the correct order, demonstrating the concept of constructor chaining effectively.