牛逼的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

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

 

posted @ 2018-10-25 02:53  toov5  阅读(168)  评论(0编辑  收藏  举报