Constructor Chaining Java Example Program
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
Basic Programs
- My First Example Java Program
- Constructor Example Java Program
- Parametrized Method Example Java Program
- Static Class and Its Usage in Java Example Program
- Static Function or Method and Its Usage in Java Example Program
- Default and Parameterized Constructor Java Example Program
- Constructor Chaining Java Example Program
- Singleton Class Using Private Constructor Java Example Program
- Constructor Overloading Example Java Program
- Simple Class and Array of Object Java Example Program
Read More Articles
- Multiple Inheritance Using Interface Example Java Program
- Single Inheritance Example Java Program
- Multilevel Inheritance Example Java Program
- Hierarchical Inheritance Example Java Program
- Find all Substrings of a given string Example Java Program
- Sum Of Three Numbers Example Java Program
- Create Matrix Example Java Program
- Twin Prime Example Java Program
- Compile Time Polymorphism Example Java Program
- Encapsulation Example Java Program