Constructor Chaining In Java

Chapter: Java Basics Last Updated: 02-05-2016 19:12:35 UTC

Program:

            /* ............... START ............... */
                
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);
	}
}
                /* ............... END ............... */
        

Output

In default constructor.
In single parameter constructor.
In double parameter constructor.
mc.a: 10
mc.b: 20

Notes:

  • Calling a constructor from the another constructor of same class is known as Constructor chaining.

Tags

Constructor Chaining, Java , Java Basics

Similar Programs Chapter Last Updated
Variables In Java Example Java Basics 03-11-2017
Java Program To Count Number Of Digits In An Integer Java Basics 29-08-2017
Java Program To Check Whether Number Is Positive Or Negative Java Basics 26-08-2017
Java Program To Multiply Two Floating Point Numbers Java Basics 25-08-2017
Java Program To Print Integer Using User Input Java Basics 25-08-2017
Java Parameterized Method Java Basics 17-05-2017
Java Float To Int Conversion Java Basics 31-03-2017
Nested Class In Java Java Basics 25-03-2017
Encapsulation In Java Java Basics 24-03-2017
Java Command Line Argument Java Basics 27-12-2016
Java Main Method Java Basics 06-11-2016
List Using Array In Java Java Basics 23-10-2016
Java Basic Program Example Java Basics 12-10-2016
Java Interface Example Java Basics 19-06-2016
Java Program For Multiplication Of Two Numbers Java Basics 18-06-2016
Java Program For Subtraction Of Two Integer Numbers Java Basics 18-06-2016
Java Program For Addition Of Two Integer Numbers Java Basics 18-06-2016
Java Program For Division Of Two Numbers Java Basics 18-06-2016
Java Class Example Java Basics 17-06-2016
Java Scanner Example Java Basics 02-05-2016
Object Array In Java Java Basics 02-05-2016
Constructor In Java Example Java Basics 02-05-2016
Java Clone Example Java Basics 02-05-2016
Casting In Java Java Basics 02-05-2016
String In Java Example Java Basics 08-08-2016
Static Method In Java Java Basics 08-08-2016
Java Method Example Java Basics 08-08-2016
Java Program To Add Two Numbers Java Basics 15-07-2016
Java Hello World Example Java Basics 06-02-2017

1