this:指代当前对象(new的对象|调用成员方法的对象)
1、在构造器的首行通过this(实参)调用本类中的其他构造器
2、区分同名成员与局部问题:
不存在同名问题,哪里有就匹配哪里,如果有局部找局部,如果有成员调用成员,默认相当于省略了this.;存在同名问题,就近原则找局部通过this.调用成员。
public class Cat {
public static void main(String[] args) {
Cat_1 cat=new Cat_1("薛","摩卡","加菲猫","灰色");
//cat.Cat_1("摩卡","加菲猫","灰色");
cat.show();
}
}
class Cat_1{
public String person;
public String name;
public String type;
public String color;
//定义带参构造
public Cat_1(String person,String name,String type,String color){
this.person=person;
this.name=name;
this.type=type;
this.color=color;
}
public void show(){
System.out.println(person+"养了一只"+color+"的"+type+"名字叫"+name);
}
}
以上代码是this关键字的使用方法示例