Start with a program:
1 classDog2 {3 PrivateString name;4 PrivateString color;5 Private intAge ;6 7 Dog (String name)8 //assign a value to name only9 {Ten This. name=name; One } A Dog (String name,string color) - //assign a value to Name,color only - { the This. name=name;//But there was a similar code before. - This. color=color; - } -Dog (String name,string color,intAge ) + //assign a value to Name,color,age only - { + This. name=name; A This. Color=color;//There have been similar codes before at This. age=Age ; - } - /*The above code drawbacks, code duplication, - and if you modify the original defined parameters (such as name), - requires extensive modification of the parameters in the method (3 modifications), causing inconvenience*/ - } in - classConstructerdemo to { + Public Static voidMain (string[] args) - { the * } $}
View Code
In this case, we can use the constructor method to invoke the constructor method (in the form of this (argument)) to resolve the above problem, and improve as follows:
1 classDog2 {3 PrivateString name;4 PrivateString color;5 Private intAge ;6 7 Dog (String name)8 //assign a value to name only9 {Ten This. name=name; One } A Dog (String name,string color) - //assign a value to Name,color only - { the //This.name=name;//But there was a similar code before. - This(name);//after improvement - This. color=color; - } +Dog (String name,string color,intAge ) - //assign a value to Name,color,age only + { A //This.name=name; at //This.color=color;//There have been similar codes before - This(Name,color);//after improvement - This. age=Age ; - } - /*The above code drawbacks, code duplication, - and if you modify the original defined parameters (such as name), in requires extensive modification of the parameters in the method (3 modifications), causing inconvenience*/ - } to + classConstructerdemo - { the Public Static voidMain (string[] args) * { $ Panax Notoginseng } -}
View Code
We should note that the call to the this constructor must be the first statement in the constructor .
That's two. Note that the This constructor must be placed in the constructor. The second is the first statement that must be a constructor.
Java Foundation Constructor method call construction method