Sunday, July 9, 2017

Constructor Chaining



/*
 * Constructor Chaining is a technique of calling another constructor from one constructor.
 * this() is used to call same class constructor where as super() is used to call super class constructor
 *
 */

 class ConstructorChaining {

public ConstructorChaining() {
System.out.println("Default constructor");
}

public ConstructorChaining(String str) {
this();
System.out.println(" constructor with single arg");
}

public ConstructorChaining(String str, int num) {
this("GAC");
System.out.println(" constructor with 2 args");
}

public ConstructorChaining(int num1, int num2, int num3) {
this("GAC", 2);
System.out.println(" constructor with 3 args");
}

public static void main(String args[]) {
ConstructorChaining obj = new ConstructorChaining(4, 8, 33);
}
}

No comments:

Post a Comment

Using Zotero for academic writing