Definition: Constructor chaining occurs through the use of inheritance.
A subclass constructor method's first task is to call its superclass'
constructor method. This ensures that the creation of the subclass
object starts with the initialization of the classes above it in the
inheritance chain.
There could be any number of classes in an inheritance chain. Every
constructor method will call up the chain until the class at the top has
been reached and initialized. Then each subsequent class below is
initialized as the chain winds back down to the original subclass. This
process is called constructor chaining.
Examples:
In the code below the Carnivore class inherits the Mammal class which inherits the Animal class:
public class Animal {
private String name;
public Animal(String name)
{
this.name = name;
System.out.println("I'm executed first.");
}
}
public class Mammal extends Animal {
public Mammal(String name)
{
super(name);
System.out.println("I'm executed second");
}
}
public class Carnivore extends Mammal{
public Carnivore(String name)
{
super(name);
System.out.println("I'm executed last");
}
}
When an instance of the Carnivore class is created the first action
of its constructor method is to call the Mammal constructor method.
Likewise, the first action of the Mammal constructor method is to call
the Animal constructor method. A chain of constructor method calls
ensures that the instance of the Carnivore object has properly
initialized all the classes in its inheritance chain.
No comments:
Post a Comment