this关键字

this

普通方法

  代表它所在函数,所属对象的引用例一

  简单说:哪个对象在调用this所在的函数,this就代表哪个对象

  this总是指向调用该方法的对象

构造方法

  用于构造函数之间互相调用,this语句只能定义在构造函数的第一行,因为初始化动作要先执行【例二】

  this总是指向正要初始化的对象 

注意

  构造器调用构造器必须把它放在第一行 构造器调用构造器的时候只能调用一次

特点

  是用于区分局部变量和成员变量同名情况

  用于构造器调用构造器

扩展

  全局变量和局部变量能否同名 当我们使用变量的时候,就近原则

    尽量不要重名,但是为了保证见名知意,参数前加”_“

注意

  this不能放到静态方法中【static】

常见错误提示

Error:Constructor call must be the first statement in a constructor

构造器调用构造器必须把它放在第一行

例题

  局部变量的名字与成员变量的名字相同,若想在该方法内使用成员变量,必须使用关键字     this     

例一

 1 public class Exam {
 2     public static void main(String[] args) {
 3 
 4         Dog dog = new Dog("老大");
 5         Dog dog1 = new Dog("老二");
 6         dog1.dogPrint(); // 老二
 7     }
 8 }
 9 
10 class Dog {
11     private String name;
12     private int age;
13 
14     Dog(String name) {
15         this.name = name;  //相当于dog1.name=name的意思
16     }
17 
18     void dogPrint() {
19         System.out.println(name);
20     }
21 
22 }

例二

 1 public class Exam {
 2     String name;
 3     int age;
 4 
 5     public Exam() {
 6         this.age = 21;
 7     }
 8 
 9     public Exam(String name, int age) {
10         this();
11         this.name = "Mick";
12     }
13 
14     private void print() {
15         System.out.println("最终名字=" + this.name);
16         System.out.println("最终的年龄=" + this.age);
17     }
18 
19     public static void main(String[] args) {
20         Exam tt = new Exam("", 0); // 随便传进去的参数
21         tt.print(); // 最终名字=Mick 最终的年龄=21
22 
23     }
24 }

应用

  当定义类中对象时,该函数内部要用到调用该函数的对象时,这时用this来表示这个对象

   但凡本类功能内部使用了本类所对应的对象,都用this表示

     用于构造函数之间互相调用

 

posted @ 2016-08-07 12:48  IT蓄水池  阅读(139)  评论(0)    收藏  举报