这里和 Python 做一下比较:
相同点:
同 Python 一样,都是对类的实例对象的一个引用。
所以,当返回实例本身时,可以采用
return this;
不同点:
1。 定义类方法时,第一参数不需要写上 this。
而 Python 需要显示的写上 self。
2。 对类成员的访问。
通常情况下,不需要加上 this 前缀。(当然加上也没关系)
特例,当参数列表中含有一个与类成员变量名字相同的变量名时,需要加上 this,以示区别。
例如:
public class Person {
String name;
void set_name(String name){
this.name = name;
}
}
3。可以采用 this 来调用该类的其他构造函数。
class Person {
String name;
Person(){
System.out.println("Person()");
}
Person(String name){
this();
this.name = name;
System.out.println("Person(String name)");
}
void set_name(String name){
this.name = name;
System.out.println(this.name);
}
}