Calling a constructor from another constructor in same class using "this" keyword:-
class Flower
{
int num = 0;
String s = new String("null");
Flower() //Default Constructor
{
this(1000,"Hello"); // calling constructor with 2 parameters
System.out.println("Danger ! Inside the default constructor");
}
Flower(int x, String y)
{
//constructor call must be the first statement in a constructor !!
this(500); //call to integer parametered constructor
//! this(s); // Can’t call two constructors within a unit!
this.num = x ; //simple num = x; is also right
s = y;
System.out.println("Danger ! Inside the double barelled constructor");
System.out.println("values >> [ "+num+" | "+s+" ]");
}
Flower(int x) {
this("Buhaha"); //call the constructor with string parameter
this.num = x ; //simple num = x; is also right
System.out.println("Danger ! Inside integer constructor");
System.out.println("values >> [ "+num+" ]");
}
Flower(String y) {
this.s = y ;
System.out.println("Danger ! Inside String constructor");
System.out.println("values >> [ "+s+" ]");
}
}
public class ConstrInThis {
public static void main(String[] args) {
Flower rose = new Flower();
}
}
Rules to be followed while using "this" keyword for calling another constructor in same class:-
You can call one constructor from another in the same class, or call the super class, with the following restrictions:
- It has to be the first line of code in the calling constructor.
- It cannot have any explicit or implicit reference to
this
. So you cannot pass an inner class (even an anonymous one if it references any instance methods), or the result of a non-static method call, as a parameter.
Hello Admin,
ReplyDeleteIt must be the primary line of code in the calling constructor.
It can't have any express or understood reference to this. So you can't pass an inward class (even a mysterious one on the off chance that it references any case techniques), or the aftereffect of a non-static strategy call, as a parameter.
Regards,
Thanks
RITU