InterviewSolution
Saved Bookmarks
| 1. |
Constructor chaining with this keyword |
|
Answer» Constructor chaining in JAVA is the process of calling one constructor with the help of another while considering the current object. It can be done in 2 ways –
Here we will take a look at how constructor chaining is done with this keyword public class Example { Example() { this(10); System.out.println("Default constructor"); } Example(int x) { this(7, 9); System.out.println("Parameterized Constructor having parameter :"+x); } Example(int a, int b) { this(10,3,4); System.out.println("Parameterized Constructor having parameters :"+a+","+b); } Example(int a, int b, int c) { System.out.println("Parameterized Constructor having parameters :"+a+","+b+","+c); } public STATIC void MAIN(String args[]) { NEW Example(); } }The output is as follows: $javac Example.java $java Example Parameterized Constructor having parameters :10,3,4 Parameterized Constructor having parameters :7,9 Parameterized Constructor having parameter :10 Default constructor |
|