1.定义:
this代表所在类的当前对象
代码理解:
**public** **class** This01 {
**public** **static** **void** main(String[] args) {
Dogg dog1 = **new** Dogg("大壮",3);
System.**out**.println("dog1.hashCode="+dog1.hashCode());
dog1.info();
Dogg dog2 = **new** Dogg("大黄",2);
dog2.info();
System.**out**.println("dog2.hashCode="+dog2.hashCode());
}
}
**class** Dogg{
**public** String name;
**public** **int** age;
**public** Dogg(String name,**int** in_age) {
**this**.name = name;
**this**.age = in_age;
System.**out**.println("this.hashCode="+**this**.hashCode());
}
<!--`hashCode返回对象的哈希值-->
**public** **void** info() {
System.**out**.println("this.hashCode="+**this**.hashCode());
System.**out**.println(**this**.name+"\t"+**this**.age);
}
}
输出:
this.hashCode=315138752
dog1.hashCode=315138752
this.hashCode=2114874018
dog2.hashCode=2114874018
小结:
哪个对象调用,this就代表哪个对象
2.使用细节
(1)this关键字可以访问本类的属性、方法、构造方法。
(2)this用于区分当前类的属性和局部变量。
(3)访问成员方法的语法:this.方法名(参数列表);
(4)访问构造方法语法:this(参数列表);注意只能在构造方法中使用(即只能在构造方法中 访问另外一个构造方法,必须放在第一条语句)。
(5)this不能在类定义的外部使用,只能在类定义的方法中使用
代码理解:
**public** **class** This02 {
**public** **static** **void** main(String[] args) {
T05 t1 = **new** T05();
t1.f2();
}
}
**class** T05{
<!--`<!--访问构造方法语法:this(参数列表);注意只能在构造方法中使用`-->-->
<!--`(即只能在构造方法中 访问另外一个构造方法`-->
<!--<!--`注意:访问构造器语法:this(参数列表);必须放在第一条语句-->`-->
**public** T05() {
<!--`这里访问T05(String name,int age)`-->
**this**("jack",100);
System.**out**.println("T05() 构造方法");
}
**public** T05(String name,**int** age) {
System.**out**.println("T05(String name,int age) 构造方法");
}
<!--`访问成员方法的语法:this.方法名(参数列表);`-->
**public** **void** f1() {
System.**out**.println("f1() 方法..");
}
**public** **void** f2() {
System.**out**.println("f2() 方法..");
<!--`调用本类的f1`-->
<!--`第一种方法`-->
f1();
<!--第二种方法-->`
**this**.f1();
}
}
输出结果:
T05(String name,int age) 构造方法
T05() 构造方法
f2() 方法..
f1() 方法..
f1() 方法..