- this关键字可以用来访问本类的属性、方法、构造器
- this用于区分当前类的属性和局部变量
- 访问成员方法的语法: this.方法名(参数列表);
- 访问构造器语法: this(参数列表):注意只能在构造器中使用(即只能在构造器中访问另外一个构造器,必须放在第一条语句)
- this不能在类定义的外部使用,只能在类定义的方法中使用,
代码举例
public class ThisDetail {
public static void main(String[] args) {
Dog03 d3 = new Dog03();
d3.t1();
}
}
class Dog03{
String name = "Wangcai";
public Dog03(String name){
System.out.println("我是第一个Dog03类的第一个构造器");
//区分:this.name指向的是类中的属性name,之间输入name指的是形参
System.out.println("this.name="+this.name);
System.out.println("name="+name);
}
public Dog03(){
//this(参数列表)可以在构造器中访问其他构造器,但是只能写在构造器的第一行
this("ErHa");
System.out.println("我是Dog03的第二个构造器");
}
public void t1(){
//this还可以指向类中的成员方法
this.t2();//目前来讲可以等价于t2();
System.out.println("我是方法t1");
}
public void t2(){
System.out.println("我是方法t2");
}
}