目录
Java虚拟机会给每个对象分配this,代表当前对象。
示例代码
- public class Constructor02 {
- public static void main(String[] args) {
- Person person = new Person("tom");
- person.info();
- }
- }
- class Person{
- String name;
-
- public Person(String name) {
- //this.name表示当前对象的属性
- this.name = name;
- }
- public void info(){
- System.out.println("name的信息:"+name);
- }
- }
内存图

使用hashCode方法验证
public class Constructor02 {
public static void main(String[] args) {
Person person = new Person("tom");
System.out.println("person.name的hashCode() = " + person.name.hashCode());
}
}
class Person{
String name;
public Person(String name) {
//this.name表示当前对象的属性
this.name = name;
System.out.println("this.name的hashCode的为"+this.name.hashCode());
}
public void info(){
System.out.println("name的信息:"+name);
}
}

总结:那个对象调用,this就代表那个对象
1、this关键字可以用来访问本类的属性、方法、构造器。
2、this用于区分当前类的属性和局部变量
3、访问成员方法:this.方法名(参数列表)
public class This01 {
public static void main(String[] args) {
T t = new T();
t.a2();
}
}
class T{
public void a1(){
System.out.println("a1方法被调用");
}
public void a2(){
System.out.println("a2方法被调用");
//使用this调用方法
this.a1();
}
}
4、访问构造器方法:this(参数列表);只能在构造器中使用,this语句必须为第一行
- public class This01 {
- public static void main(String[] args) {
- T t = new T();
- }
- }
- class T{
- String name;
-
- public T() {
- //使用this调用构造方法,this必须在第一行
- this("tom");
- System.out.println("T类的无参构造器被调用");
- }
-
- public T(String name) {
- this.name = name;
- System.out.println("T类的有参构造器被调用");
- }
- }

5、this不能在类定义的外部使用,只能在类定义的方法中使用。