java基础之this的用法 10.13

this:
1.返回调用当前方法的对象的引用。
public class Leaf{
private int i=0;
public Leaf increament(){
i++;
return this;
}
public static void main(String[] args){
Leaf x= new Leaf();
x.increment().print();
Leaf y= new Leaf();
y.increment().print();
}
}

this表示Leaf类的实例 当执行x.increment(),this表示实例x的引用。同理执行y.increment(),this表示实例y的引用。

2.在构造方法中调用当前类的其他构造方法.
定义了3个person类的构造方法,分别是无参,有一个参数,有两个参数,实现代码的重复利用,使用this()和this(_name)来调用person()和person(String _name)
在使用this调用其他的构造方法时,必须放在构造方法的开始处,否咋不会编译
public class Person{
private String name;
private int age;
private String sex;
public Person(){
sex="male";
}
public Person(String _name){
this();
name=_name;
}
public Person(String _name,int _age){
this(_name);
age=_age;
}
}
3.当方法参数名和成员变量名相同,用于区分参数名和成员变量。
setter方法的参数名和成员变量名相同,this.name表示成员变量名,name表示参数名。
public class Person{
private String name;
privae int age;
public void setName(String name){
this.name=name;
}
public void setAge(int age){
this.age=age;
}
}

原文地址:https://www.cnblogs.com/weijingboke/p/5955094.html