Java Constructor Chaining - The Coding Shala
Home >> Learn Java >> Java Constructor Chaining
Output:
Output:
Output:
Java Constructor Chaining
Constructor Chaining is calling a constructor from another constructor of the same class is known as Constructor chaining. Constructor chaining allows us to maintain initialization from a single place while providing multiple constructors. We can pass parameters through different constructors. Constructor chaining can be done in two ways:
- Within the same class
- From base class
Point to Remember: When we are calling a constructor from another constructor then this() should always be the first line of the constructor and there should be at least one constructor without this() keyword. The order does not matter in Constructor chaining.
Constructor chaining within the same class
We use this() keyword to achieve constructor chaining within the same class. The following example explains constructor chaining within the same class:
class Student{ Student(){ this(1); System.out.println("This is default constructor"); } Student(int id){ this(id, "Akshay"); System.out.println("Passing name as additional parameter"); } Student(int id, String name){ System.out.println(id+" "+name); } public static void main(String[] args){ new Student(); } }
1 Akshay Passing name as additional parameter This is default constructor
We can also change the order of calling constructor, it does not matter. The following example explains it:
class Addition{ Addition(){ System.out.println("Default constructor"); } Addition(int a){ this(); System.out.println("First one is: "+ a); } Addition(int a, int b){ this(5); System.out.println("Sum is: "+(a+b)); } public static void main(String[] args){ new Addition(5, 4); } }
Default constructor First one is: 5 Sum is: 9
Constructor chaining from the base class
We use super() keyword for constructor chaining to the other class. Here also the first line should be super() in the constructor. The following is an example of constructor chaining from another class:
class base{ base(){ System.out.println("base class default constructor"); } base(String name){ System.out.println("Student name is: "+name); } } class child extends base{ child(){ System.out.println("child default constructor"); } child(String name){ super(name); System.out.println("This is child class construtor"); } public static void main(String[] args){ new child("Akshay"); } }
Student name is: Akshay This is child class construtor
Other Posts You May Like
Comments
Post a Comment