具体的:我们可以用 this 来区分 属性 和 局部变量。比如: this.name = name;
(1)在任意方法或构造器内,可以使用"this.属性"或"this.方法"的方式,调用当前对象属性或方法,增强程序的阅读性。不过,通常我们都习惯省略this。
(2)当形参与成员变量同名时,如果在方法内或构造器内需要使用成员变量,必须显式的使用"this.变量"的方式,表明此变量是属性,而非形参。
(3)使用 this 访问属性和方法时,如果在本类中未找到,会从父类中查找。
Demo:
1 public class Person {
2 private String name;
3 private int age;
4
5 public Person(String name, int age) {
6 this.name = name;
7 this.age = age;
8 }
9 public void getInfo() {
10 System.out.println("姓名" + name);
11 this.speak();
12 }
13 public void speak() {
14 System.out.println("年龄" + this.age);
15 }
16 }
Demo2:当前正在操作本方法的对象称为当前对象。
1 public class PersonTest {
2
3 public static void main(String[] args) {
4 Person per1 = new Person("张三") ;
5 Person per2 = new Person("李四") ;
6 per1.getInfo() ; // 当前调用getInfo()方法的对象是per1
7 per2.getInfo() ; // 当前调用getInfo()方法的对象是per2
8 boolean b = per1.compare(per2);
9 }
10 }
11
12 class Person {
13 String name;
14 Person(String name) {
15 this.name = name;
16 }
17 public void getInfo() {
18 System.out.println("Person类" + this.name);
19 }
20 public boolean compare(Person p) {
21 return this.name == p.name;
22 }
23 }
(1)我们在类的构造器中,可以显式的使用"this(形参列表)"方式,调用本类中指定的其他构造器;
(2)构造器中不能通过"this(形参列表)"方式调用自己;
(3)如果一个类中有n个构造器,则最多有 n - 1构造器中使用了"this(形参列表)";
(4)规定:"this(形参列表)"必须声明在当前构造器的首行;
(5)构造器内部,最多只能声明一个"this(形参列表)",用来调用其他的构造器;
Demo:
1 public class Person {
2 private String name;
3 private int age;
4 public Person() { //无参构造器
5 System.out.println("新对象实例化");
6 }
7 public Person(String name) {
8 this(); //调用本类中的无参构造器
9 this.name = name;
10 }
11 public Person(String name, int age) {
12 this(name); //调用有一个参数的构造器
13 this.age = age;
14 }
15 public void getInfo() {
16 System.out.println("Person类" + this.name);
17 }
18 public boolean compare(Person p) {
19 return this.name == p.name;
20 }
21 }
原文:https://www.cnblogs.com/niujifei/p/13773094.html