1.this指向当前的对象,更确切的说this是执行当前对象的一个引用变量,好比如下代码,输出的结果的地址值是相同的,也就是this指向了P这个对象this
1 public class Person { 2 String name; 3 int age; 4 public void say(){ 5 6 7 System.out.println("this:"+this); 8 } 9 public static void main(String[] args) { 10 Person p=new Person(); 11 p.say(); 12 System.out.println("p:"+p); 13 } 14 }
2.在一个类中,当这个类中的成员变量被与他同名的构造方法中的局部变量隐藏时,咱们能够经过this.变量名调用。以下代码:当第7行咱们不用this关键字时,输出是“张三吃”,反之“李四吃”,这里的this就是指向11行的p,至关于p.name。spa
1 public class Person { 2 String name="李四"; 3 int age; 4 5 public Person(){ 6 String name="张三"; 7 System.out.println(this.name+"吃"); 8 9 } 10 public static void main(String[] args) { 11 Person p=new Person(); 12 13 } 14 }
3.当构造方法调用构造方法时,咱们能够用this([参数列表])来调用,无参用this(),如如下代码。须要追的是this必须书写在第一行。打印时先打印this的结果:12行,而后打印7行。code
1 public class Person { 2 String name; 3 int age; 4 5 public Person(String name){ 6 this("李四",23); 7 System.out.println("一个变量的构造方法"); 8 9 } 10 public Person(String name,int age){ 11 12 System.out.println("两个变量的构造方法"); 13 } 14 public static void main(String[] args) { 15 Person p=new Person("张三"); 16 } 17 }