1、将当前对象的引用传递给另外的类
//this:把对当前对象的引用传递给另外的类
public class TestThis {
public static void main(String[] args) {
new Person().eat(new Apple());
}
//人
static class Person{
public void eat(Apple apple){
Apple peeled=apple.getPeeled();
System.out.println(“end”);
}
}
//苹果
static class Apple{
Apple getPeeled(){
return Peeler.peel(this);
}
}
//剥皮
static class Peeler{
static Apple peel(Apple apple){
return apple;
}
}
}
输出结果:
end
解析:人调用eat方法,需要传入apple,从Apple类中查找apple对象,在Peeler类中找到apple
2、在构造器中的应用
//this在构造器中的使用
/*因为创建对象时没有传入参数,故调用的是构造器4创建对象,执行构造器4时,调用构造器3,执行构造器3时,
-
根据传入的参数类型,先执行构造器1,因此输出int=50,然后将参数赋值给全局变量s
-
继续执行,输出StringAndInt,然后构造器4打印出default,
-
最后执行对象的方法printPeelCount(),输出结果*/
public class Floor {
int peelCount=0;
String s=“initial value”;
//构造器1
Floor(int peels){
peelCount=peels;
System.out.println(“int=”+peelCount);
}
//构造器2
Floor(String ss){
s=ss;
System.out.println(“String=”+s);
}
//构造器3
Floor(String s,int peels){
this(peels);//调用其他构造器
this.s=s;
System.out.println(“StringAndInt”);
}
//构造器4
Floor(){
this(“hello”,50);
System.out.println(“default”);
}
void printPeelCount(){
System.out.println(“count=”+peelCount+" s="+s);
}public static void main(String[] args) {
Floor f = new Floor();
f.printPeelCount();
}
}
输出结果为:
int=50
StringAndInt
default
count=50 s=hello