Java Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | public class JavaConstructorChainingExample { int a; int b; public JavaConstructorChainingExample() { System.out.println("In default constructor."); } public JavaConstructorChainingExample(int a) { this(); this.a = a; System.out.println("In single parameter constructor."); } public JavaConstructorChainingExample(int a, int b) { this(a); this.b = b; System.out.println("In double parameter constructor."); } public static void main(String a[]) { JavaConstructorChainingExample mc = new JavaConstructorChainingExample(10, 20); System.out.println("mc.a: " + mc.a); System.out.println("mc.b: " + mc.b); } } |
Output:
1 2 3 4 5 6 7 | In default constructor. In single parameter constructor. In double parameter constructor. mc.a: 10 mc.b: 20 |
Calling a constructor from the another constructor of same class is known as Constructor chaining.