牛逼的This使用

牛逼的This使用

今天看到一个很不错的this使用demo:

package com.toov5.Reordering;

class Message1{
    private Channel channel;
    private String title;
    private String content;
    
    public Message1(Channel channel,String title, String content) {
        this.channel=channel;
        this.title=title;
        this.content=content;
    }
    public void send(){
        if (this.channel.isConnect()) {
            System.out.println("发送消息title"+this.title+"conten"+this.content);
            
        }else {
            System.out.println("无法发送");
        }
    }
    
}

class Channel{
    private Message1 message;
    public Channel(String title, String content) {
        this.message=new Message1(this, title, content);
        this.message.send();
    }
    public boolean isConnect(){
        return true;
    }
}

public class ThisTest {
     public static void main(String[] args) {
        Channel ch = new Channel("toov5", "happy");
//        Message message = new Message(ch, "toov2", "happy");
//        message.send();
    }
    
    
    
}

 

this 代表当前对象的引用

  

成员对象 应该又对象去调用

this代表当前的对象地址

package com.toov5.test;

class Car{
    private int num;
    public void setNum(int num) {
        this.num=num;  //这里面的this 代表了 C 这个对象地址哦     局部变量给成员变量赋值  get方法中 return this.num  this可以不写默认
    }
public void run() {
        System.out.println("数量"+num);
    }
}

class Demo2_Car {
   
     public static void main(String[] args) {
        
         Car c = new Car();
         c.setNum(123);
         c.run();
    }
}

 

如果不用this 就近原则的话 就是给自己复制了 name 给 name赋值  (区分成员变量 和 局部变量了  重名情况)

num 已经被私有了,不能到别的类里面去调用

然后 先用this

等创建完了对象 去调用时候 就代表那个对象了

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值