Constructor Chaining In Java programming

Java 8Object Oriented ProgrammingProgramming

Constructor chaining refers to calling a constructor from other constructor. It is of two types.

  • Within same Class − Use this() keyword to refer to current class constructor. Make sure that this() is the first statement of the constructor and there should be at least one constructor without using this() statement.

  • From super/base Class − Use super() keyword to refer to parent class constructor. Make sure that super() is the first statement of the constructor.

Example

 Live Demo

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

[ a= 10]
[ a= 11, b = 12]
[ a= -1]
[ a= -1, b = -1]
raja
Published on 01-Nov-2018 05:16:14
Advertisements