English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Constructor Chaining in Java Programming

Constructor chaining is the process of calling one constructor from another constructor. It has two types.

  • in the same class-usethis()Keyword to refer to the current class constructor. Ensure that thisthis()is the first statement in the constructor and should have at least one that does not use thethis()statement in the constructor.

  • from super/base class-usesuper()Keyword to refer to the parent class constructor. Ensure that thissuper()is the first statement in the constructor.

Example

class A {
   public int a;
   public A() {
      this(-1);
   }
   public A(int a) {
      this.a = a;
   }
   public String toString() {
      return "[ a= " + this.a + "]";
   }
}
class B extends A {
   public int b;
   public B() {
      this(-1,-1);
   }
   public B(int a, int b) {
      super(a);
      this.b = b;
   }
   public String toString() {
      return "[ a= " + this.a + ", b = " + b + "]";
   }
}
public class Tester {
   public static void main(String args[]) {
      A a = new A(10);
      System.out.println(a);
      B b = new B(11,12);
      System.out.println(b);
      A a1 = new A();
      System.out.println(a1);
      B b1 = new B();
      System.out.println(b1);
   }
}

Output result

[ a= 10]
[ a= 11, b = 12]
[ a= -1]
[ a= -1, b = -1]