1.使用在类中,可以用来修饰属性、方法、构造器
2.表示当前对象或者是当前正在创建的对象
3.当形参与成员变量重名时,如果在方法内部需要使用成员变量,必须添加this来表明该变量时类成员
4.在任意方法内,如果使用当前类的成员变量或成员方法可以在其前面添加this,增强程序的阅读性
5.在构造器中使用“this(形参列表)”显式的调用本类中重载的其它的构造器
5.1 要求“this(形参列表)”要声明在构造器的首行!
5.2 类中若存在n个构造器,那么最多有n-1构造器中使用了this。
【例子】
- public class TestPerson {
- public static void main(String[] args) {
- Person p1 = new Person();
- System.out.println(p1.getName() + ":" + p1.getAge());
- Person p2 = new Person("DannyWu", 1);
- int temp = p2.compare(p1);
- System.out.println(temp);
- }
- }
- class Person {
- private String name;
- private int age;
- public Person() {
- this.name = "DannyWu";
- this.age = 1;
- }
- public Person(String name) {
- this();
- this.name = name;
- }
- public Person(String name, int age) {
- this(name);
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public void eat() {
- System.out.println("eating");
- }
- public void sleep() {
- System.out.println("sleeping");
- this.eat();
- }
- // 比较当前对象与形参的对象的age谁大。
- public int compare(Person p) {
- if (this.age > p.age)
- return 1;
- else if (this.age < p.age)
- return -1;
- else
- return 0;
- }
- }

我的微信
有问题微信找我