作用
- this 可以调用类的属性、方法和构造器
- 当方法的形参和类的属性相同的需要使用 this 区分,即 this 可以用来区分属性和局部变量
例如:
class Person{
private String name;
private int age;
private Person(){
}
private void setName(String name){
this.name = name;
}
private String getName(){
return name;
}
private void setAge(int age){
this.age = age;
}
private int getAge(){
return age;
}
}
注意
- 可以在类的构造器中使用 this(形参列表) 的方式,调用本类中重载的其他的构造器
- 明确:构造器中不能通过 this(形参列表) 的方式调用自身构造器
- 如果一个类中声明了n个构造器,则最多有 n - 1个构造器中使用了 this(形参列表)
- this(形参列表) 必须声明在类的构造器的首行
- 在类的一个构造器中,最多只能声明一个 this(形参列表)