您的位置:首页 > 其它

什么时候会用到this()构造方法?

2016-03-24 16:21 337 查看
Where to use this() constructor call?

The this() constructor call should be used to reuse the constructor in the constructor. It maintains the chain between the constructors i.e. it is used for constructor chaining. Let’s see the example given below that displays the actual use of this keyword.

package com.hotmail.henrytien;

public class Student14 {
int id;
String name;
String city;
public Student14(int id,String name) {
this.id = id;
this.name = name;
}
public Student14(int id,String name, String city) {
this(id, name);
this.city = city;
}
void display() {
System.out.println(id + "  "+ name + " " + city);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Student14 s1 = new Student14(110,"Henry");
Student14 s2 = new Student14(110,"Berlin","Germany");
s1.display();
s2.display();
}

}


output:

110 Henry null

110 Berlin Germany

Rule: Call to this() must be the first statement in constructor.

compiler will be warning:

Constructor call must be the first statement in a constructor.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: