zoukankan      html  css  js  c++  java
  • 牛逼的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

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

  • 相关阅读:
    BZOJ2219数论之神——BSGS+中国剩余定理+原根与指标+欧拉定理+exgcd
    Luogu 3690 Link Cut Tree
    CF1009F Dominant Indices
    CF600E Lomsat gelral
    bzoj 4303 数列
    CF1114F Please, another Queries on Array?
    CF1114B Yet Another Array Partitioning Task
    bzoj 1858 序列操作
    bzoj 4852 炸弹攻击
    bzoj 3564 信号增幅仪
  • 原文地址:https://www.cnblogs.com/toov5/p/9847587.html
Copyright © 2011-2022 走看看