Calling constructors from constructors
Sited By<think in java> p118
When you write several constructors for a class, there is times when you're
Constructor from another to avoid duplicating code.
When you write several constructors for a class, sometimes you need to call another constructor in a constructor to avoid repeating the code.
You can make such a call by using the This keyword.
At this point you can do this by calling the This keyword.
Normally, when you say this , it's in the sense of ' this object ' or ' The current object, ' and by
itself it produces the reference to the current object.
< Span style= "FONT-SIZE:11PT;" >
In a constructor, the this keyword takes on a different meaning when you give it an argument list .
But inside the constructor, when you give it some formal parameters, the This keyword can represent a different meaning.
< Span style= "FONT-SIZE:11PT;" >it makes an explicit call to The constructor this matches that argument list. < /span>
< Span style= "FONT-SIZE:11PT;" > that's you. It can be displayed by invoking a constructor that is the same as the number of its formal parameters.
Thus you have a straightforward-to-call other constructors.
So you can easily invoke other construction methods.
: initialization/flower.java// calling constructors with "This" import static net.mindview.util.print.*;p ublic class flower {int petalcount = 0; string s = "Initial value"; Flower (int petals) {petalcount = petals;print ("constructor w/ int arg only, petalcount= "+ petalcount);} Flower (STRING&NBSP;SS) {print ("constructor w/ string arg only, s = " &NBSP;+&NBSP;SS); s = ss;} Flower (string s, int petals) {this (petals);//! this (s); // can ' T call two!this.s = s; // Another use of "This" print ("string & int args ");} Flower () {this ("Hi", 47);p rint ("default constructor (No args)");} Void printpetalcount () {//! this (one); // not inside non-constructor!print (" Petalcount = " + petalCount + " s = "+ s);} Public static void main (String[] args) {flower x = new flower (); X.printpetalcount ();}} /* Output:Constructor w/ int arg only, petalCount= 47String & int argsdefault constructor (No args) petalcount = 47 s = hi*///:
The function of the This keyword-Displays the call constructor.