this 关键字
在堆空间内存分配时还会给每个对象分配 this
this 的本质:就是指向当前对象
使用细节
-
this 不能在类定义的外部使用,只能在类定义的方法中使用
-
this 关键字可以用来访问本类的属性、方法、构造器
-
this 用于区分当前类的属性和局部变量
-
访问成员方法的语法:this.方法名(参数列表)
-
访问构造器语法:this(参数列表); 注意只能在构造器中使用(即只能在构造器中访问另外一个构造器,必须放在第一条语句)
代码示例
public class this关键字 {
public static void main(String[] args) {
thiss th = new thiss(18, "jackson");
System.out.println("th.age:" + th.age);
System.out.println("th.name:" + th.name);
}
}
class thiss {
int age;
String name;
public thiss(int age, String name) {
this.age = age;
this.name = name;
}
}
th.age:18
th.name:jackson
this.name , this.age
指向的都是对象中的属性,而不是局部变量,实现了局部变量和全局变量同名但是作用域不同
练习题
定义 Person 类,里面有 name、age 属性,并提供 compareTo 比较方法,用于判断是否和另一个人相等,提供测试类 TestPerson,用于测试,名字和年龄完全一样,就返回 true,否则返回 false
public class homework2 {
public static void main(String[] args){
person p = new person(18,"jackson");
person testperson = new person(18,"jackson");
System.out.print(p.compareto(testperson));
}
}
class person{
int age;
String name;
public person(int age,String name){
this.name = name;
this.age = age;
}
public boolean compareto(person p){
return this.name.equals(p.name) && this.age == p.age;
}
}