java基础 二 (this关键字) ~ 2020-10-

2020-10-19  本文已影响0人  XX杰

声明:this关键字必须放在非静态方法里面##

this关键字代表自身,在程序中主要的使用用途有以下几个方面:

  1. 使用this关键字引用成员变量
  2. 使用this关键字在自身构造方法内部引用其它构造方法
  3. 使用this关键字代表自身类的对象
  4. 使用this关键字引用成员方法

其中124比较常见 也比较好理解

// 在自身构造方法内部引用其它构造方法
public UserExample() {
        this(null);
    }
// 引用成员变量
public UserExample(String name, Integer age) {
        this.name = name;
        this.age = age;
        this.myDoll = new MyDoll("prize");
    }
// 1. 调用本类方法
    public String introYourself() {
        return this.whoAreU() +
                this.haoOldAreU() +
                "\r\n whoAmI@ " + this.myDoll.whoAmI() +
                "\r\n whoAreSuper@ " + this.myDoll.whoAreSuper();
    }

其中第三情况,本人不经常使用
使用this关键字代表 **自身类的对象 **

比如handler.sendMessage()中
msg.target = this;
// 其中this,就是指 调用sendMessage的对象

vmConf.remember();  方法里面 return this;
返回的是vmconf自己本身
上一篇 下一篇

猜你喜欢

热点阅读