Constructor Chaining Example in Java
On this page (11sections)
Introduction
Constructor Chaining is a classic Java console program that demonstrates the concept with complete source code and sample output. These programs cover your first Java class, constructors, methods and simple OOP building blocks.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Definition
Constructor chaining is calling a constructor from the another constructor of the same class.
Chaining Constructor Characteristics In Java
- Call another constructor using this() keyword in the same class.
- The class has two or more constructors.
- Each constructor has various type of arguments.
Syntax
class ClassName{
public ClassName() {
//Do Something
}
public ClassName(String string) {
//Calling the Constructor without any parameters - Chaining
this();
//Do something
}
}
Constructor Chaining Example Program
public class ConstructorChaining {
public static void main(String[] args) {
ChainingClass object = new ChainingClass("This is the third ", "Chaining Constructor");
}
}
class ChainingClass{
public ChainingClass() {
System.out.println("This is the first Chaining Constructor");
}
public ChainingClass(String string) {
//Calling the Constructor without any parameters
this();
System.out.println(string);
}
public ChainingClass(String string1, String string2) {
//Calling the constructor with one parameter - Chaining
this("This is the second Chaining Constructor");
System.out.println(string1+string2);
}
}
Sample Output
This is the first Chaining Constructor
This is the second Chaining Constructor
This is the third Chaining Constructor
When to use
Use this constructor chaining example when learning or revising core Java syntax.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
ChainingClass object = new ChainingClass("This is the third ", "Chaining Constructor");updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
A
println/printcall writes text to the console — part of the sample output below. -
A
println/printcall writes text to the console — part of the sample output below. -
Compare your console output with the sample output for Constructor Chaining to confirm the program behaves correctly.
Best Practices
- Name classes in PascalCase and follow one public class per file when starting out.
- Keep
mainshort — delegate work to other methods as programs grow.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.