How can a constructor invoke another constructor of the same class?
Answer:
A constructor can invoke another constructor of the same class using the this
keyword .
In Java, the `this()` keyword can be used within a constructor to call another constructor of the same class. This is useful for constructor chaining, where one constructor can invoke another to reduce redundancy.
Hereâs an example using a parent class `Animal` and a subclass `Mammal`, where the `this()` keyword is used in the `Mammal` class to invoke another constructor of the same class.
Example:
// Parent class
class Animal {
String name;
int age;
// Constructor 1
public Animal(String name) {
this.name = name;
System.out.println("Animal constructor with name: " + name);
}
// Constructor 2
public Animal(String name, int age) {
this(name); // Calls the other constructor of the same class
this.age = age;
System.out.println("Animal constructor with name and age: " + name + ", " + age);
}
}
// Subclass
class Mammal extends Animal {
String type;
// Constructor 1
public Mammal(String name, int age, String type) {
super(name, age); // Calls the parent class constructor
this.type = type;
System.out.println("Mammal constructor with type: " + type);
}
// Constructor 2
public Mammal(String name, String type) {
this(name, 0, type); // Calls the other constructor of the same class
System.out.println("Mammal constructor with default age");
}
}
public class Main {
public static void main(String[] args) {
// Creating a Mammal object using the second constructor
Mammal mammal = new Mammal("Lion", "Carnivore");
// Creating a Mammal object using the first constructor
Mammal mammal2 = new Mammal("Elephant", 10, "Herbivore");
}
}
Output:
Animal constructor with name: Lion
Animal constructor with name and age: Lion, 0
Mammal constructor with type: Carnivore
Mammal constructor with default age
Animal constructor with name: Elephant
Animal constructor with name and age: Elephant, 10
Mammal constructor with type: Herbivore
Explanation:
- Parent Class (`Animal`):
- The `Animal` class has two constructors:
- One that accepts a `name`.
- Another that accepts both `name` and `age`, and it invokes the first constructor using `this(name)`.
- Subclass (`Mammal`):
- The `Mammal` class has two constructors:
- One that accepts a `name`, `age`, and `type`, and it invokes the parent class's constructor using `super(name, age)`.
- Another that accepts a `name` and `type` but invokes the other constructor in the same class using `this(name, 0, type)`.
In this way, constructor chaining is achieved both in the parent class (`Animal`) and the subclass (`Mammal`).