18 this关键字

18 this关键字

本质

谁调用,代表谁

常用操作

1.调用本类的属性

​ this.属性名

//例如类中的Set方法
public void setAge(int age){
    this.age=age;
    //this.age代表当前调用setAge()方法的对象所对应的Age值
}

2.调用本类的构造方法(函数)

this(形参1,形参2......形参n),其中形参是根据构造方法来安排的

public class Person{
   private int age;
   public Person(){
   
   }
   public Person(int age){
       this();//一定要放在首行
       //用this(形参,形参2.....形参n)时,
       //要留一个构造函数作为出口,默认留着无参构造(自己写出来)作为出口
       this.age=age;
   }
}

3.表示当前对象

this
//以String类中的toString方法为例
public String toString() {
        return this;//返回的是调用toString方法的字符串本身
}
//常规来讲,如果是打印变量默认调用的都是toString方法,默认其实打印为地址,
//但String类中重写了这个方法,所以返回值就是调用的字符串
原文地址:https://www.cnblogs.com/SSSzhanglingzhi/p/14055309.html