Java学习笔记—this关键字

引出this

image
image

  • 解决问题
    image
    this指向 调用该构造器的对象(谁调用指向谁)

this本质

image

  • 在创建对象的时候,在对象空间中就默认隐藏了this量指向对象本身。

this的使用细节

1.this关键字可以用来访问本类的属性、方法、构造器
2、this用于区分当前类的属性和局部变量
3、访问成员方法的语法:this.方法名(参数列表);
image
image
4、访问构造器语法:this(参数列表);注意只能在构造器中 使用(即只能在构造器中访问另外一个构造器,必须第一条语句)
image
5、this不能在类定义的外部使用,只能在类定义的方法中使用

this练习

image

public class Test04{
	public static void main(String[] args){

		Person p = new Person("xiaoli", 20);
		TestPerson p2 = new TestPerson("xiaoming", 19);
		boolean res = p.compareTo(p2);
		System.out.println(res);
	}
}
class Person{
	String name;
	int age;
	public Person(String name, int age){
		this.name = name;
		this.age = age;
	}
	public boolean compareTo(TestPerson p){
		if (p.name == this.name && p.age == this.age){
			return true;
		}else {
			return false;
		}
	}
}
class TestPerson{
	String name ;
	int age ;
	public TestPerson(String name, int age){
		this.name = name;
		this.age = age;
	}
}
posted @ 2022-04-20 17:20  云吞豚  阅读(31)  评论(0)    收藏  举报