一、this引入
java虚拟机会给每个对象分配this,代表当前对象。
哪个对象调用,this就代表哪个对象。
class Dog {
public String name;
public int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
public void info() {
//输出属性信息
System.out.println(this.name + "\t" + this.age + "\t");
}
}
二、深入理解this
使用hashCode()方法:返回对象的哈希码值。针对不同的对象返回不同的整数(这一般是通过将该对象的内部地址转换成一个整数来实现的)。
public class this01 {
public static void main(String[] args) {
Dog dog1 = new Dog("puppy111", 1);
System.out.println("dog1的hashCode=" + dog1.hashCode());
dog1.info();
System.out.println();
Dog dog2 = new Dog("222puppy", 2);
System.out.println("dog1的hashCode=" + dog2.hashCode());
dog2.info();
}
}
class Dog {
public String name;
public int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
System.out.println("this.hashCode=" + this.hashCode());
}
}

本笔记是对韩顺平老师的Java课程做出的梳理。方便本人和观看者进行复习。
课程请见: https://www.bilibili.com/video/BV1fh411y7R8/?spm_id_from=333.999.0.0&vd_source=ceab44fb5c1365a19cb488ab650bab03
三、this的注意事项和使用细节
- this 关键字可以用来访问本类的属性、方法、构造器
- this 用于区分当前类的属性和局部变量
- 访问成员方法的语法:this.方法名(参数列表);
- 访问构造器语法:this(参数列表); 注意只能在构造器中使用(即只能在构造器中访问另外一个构造器, 必须放在第一条语句)
- this 不能在类定义的外部使用,只能在类定义的方法中使用。
补充说明3.
class T {
public void f1() {
System.out.println("f1()方法..");
}
public void f2() {
System.out.println("f2()方法..");
//第1种方式
f1();
//第2种方式
this.f1();
}
}
补充说明4.
public class this01 {
public static void main(String[] args) {
T t1 = new T();
}
}
class T {
public T() {
this("jack", 1);
System.out.println("T() 构造器");
}
public T(String name, int age) {
System.out.println("T(String name, int age) 构造器");
}
}

四、例题
定义Person类,里面有name、age属性,并提供compareTo比较方法,用于判断·是否和另一个人相等,提供测试类TestPerson用于测试,名字和年龄完全一样,就返回true,否则返回false
public class TestPerson {
public static void main(String[] args) {
Person xiaohong = new Person("xiaohong",13);
Person daming = new Person("daming",20);
if(xiaohong.compareTo(daming)) {System.out.println("相等");}
else{System.out.println("不同");}
}
}
class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public boolean compareTo(Person tmp) {
if(this.name == tmp.name && this.age == tmp.age) {
return true;
} else {
return false;
}
}
}
本笔记是对韩顺平老师的Java课程做出的梳理。方便本人和观看者进行复习。
课程请见: https://www.bilibili.com/video/BV1fh411y7R8/?spm_id_from=333.999.0.0&vd_source=ceab44fb5c1365a19cb488ab650bab03
本文详细介绍了Java中的this关键字,包括其基本概念、在构造器和成员方法中的应用,以及hashCode的使用和this的注意事项。通过实例演示了如何在类中正确地使用this进行属性和方法访问。
1079

被折叠的 条评论
为什么被折叠?



