this关键字的运用

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值