Other overloaded constructors of this class can be called in the constructor, and instead of using the constructor name to invoke another constructor, it should be called using the Java-specific this (...).
This (...) method must appear in the first row in the constructor to invoke the other overloaded constructors. Parameters must be strictly matched when called.
The advantage of this invocation is that a constructor can provide good and class code structures by invoking other constructors to enable reuse without having to rewrite the code already in the other constructors.
Public class Teacher {
private String name;
PrivateString gender;
private int age;
Public Teacher (String name) {
This (name, "male");
System.out.println ("First row constructor");
}
Public Teacher (String name,string gender) {
This (name,gender,45);
System.out.println ("second row constructor");
}
Public Teacher (String name,string Gender, int.) {
THIS.name = name;
This.gender = gender;
This.age = age;
System.out.println ("This is the third constructor");
}
public void SetName (String name) {
THIS.name = name;
}
Public String GetName () {
return name;
}
public void Setgender (String gender) {
This.gender = gender;
}
Public String Getgender () {
return gender;
}
public void Setage (int.) {
if (age > 100) {
Return
}
this.age = age;
public int Getage () {
return age;
public void Lecture () {
}
public void doexec () {
}
public String Say () {
string str =" I am "+ name +", gender "+gender +", age "+age;
return str;
}
}
called in the TestConstructor class
public class TestConstructor {
public static void Main (string[] args) {
Teacher t = new Teacher ("Zhang San");
System.out.println (T.say ());
Teacher T1 = new Teacher ("John Doe", "female");
System.out.println (T1.say ());
Teacher t2 = new Teacher ("Harry", "Male", 33);
System.out.println (T2.say ());
}
}
Output results
This is the third constructor
Second Row constructor
First Row constructor
I'm Zhang San, sex guy, age 45.
This is the third constructor
Second Row constructor
I'm John Doe, sex girl, age 45
This is the third constructor
I'm Harry, sex guy, age 33.
Article Source: http://blog.csdn.net/baidu_30360575/article/details/50548695
Java uses this keyword to invoke this class of overloaded constructors