1. Technology
Send to a Friend via Email

Constructor Chaining


Man using computer
Phil Boorman/Cultura/Getty Images

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.


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)
     System.out.println("I'm executed second");
 public class Carnivore extends Mammal{
   public Carnivore(String 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.


# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Related Video
Create Bullet, Number, and Definition Lists in HTML
  1. About.com
  2. Technology
  3. Java
  4. Java Glossary
  5. C
  6. Definition and Examples of Constructor Chaining

©2014 About.com. All rights reserved.