第五章 this 关键字
1.this关键字只能在方法的内部使用,表示对调用该方法的那个对象的引用。即当前对象的引用。
public class Leaf{
int leafCount = 0;
public Leaf increment(){
leafCount++;
}
public static void main(String[] args){
Leaf leaf = new Leaf();
leaf.increment().increment().increment();
}
}
Leaf 的increment方法对叶子数加1,并返回当前叶子对象的引用。所以可以连续的调用increment方法。
2.在构造器中利用this调用同一个类中的其他构造器,但只能调用一个。此外,使用this调用的构造器必须放在构造器的第一行。
class Person{
int age;
String name;
Person(int age){
this.age = age;
}
Person(String name){
this.name = name;
}
Person(int age ,String name){
this(age);//调用Person(int age)
// this(name); 错误
this.name = name;
}
}