在java编程思想中有这样一段话:通常写this的时候,都是指“这个对象”或者“当前对象”,而且它本身表示对当前对象的引用。在构造器中,如果为this添加了参数列表,那么就有不同的含义。这将产生对符合此参数列表的某个构造器的明确调用;这样调用其他构造函数就有了直接的途径。
简而言之:1.this指代当前对象的引用;2.this指代构造器(根据参数不同)。
1. This 指代当前类的引用
例子1:重名时,区分成员变量和局部变量
class Person{
String name;
void setName(String name){this.name=name;}
public static void main(String[] args){
Person p1= new Person();
p1.setName("dd");
System.out.println(p1.name);
}
}
例子2:java编程思想85页例子,指代当前类的引用
class Person{
public void eat(Apple apple){
Apple peeled = apple.getPeeled();
System.out.println("Yummy");
}
}
class Peeler{
static Apple peel(Apple apple){
//....remove peel
return apple;
}
}
class Apple{
Apple getPeeled(){
return Peeler.peel(this);
}
}
public class This{
public static void main(String args[]){
new Person().eat(new Apple());
}
}
例子3:return this,返回当前类的引用
public class This{
int i = 0;
This increment(){
i += 2;
return this;
}
void print(){
System.out.println("i = " + i);
}
public static void main(String args[]){
This x = new This();
x.increment().increment().print();
}
}
结果为:4
2.构造器中使用this

super
super的用法和this差不多,但super指代的是父类
1.通过super关键字访问父类成员变量、方法
2.super如果用在构造方法中,要放第一行
网友评论