this

this使用范围  

1、在类的方法定义中使用的this关键字代表调用该方法对象的引用。

2、当必须指出当前使用方法的对象是谁时,要使用关键字this。

3、有时使用this可以处理方法中成员变量和参数重名的情况。

4、this可以看做是一个变量,它的值是当前对象的引用。

注:this一般出现在方法中,当方法没有被调用时。并不知道this指向那个具体的对象。

当某个对象调用有this的方法时,this就指向调用这个方法的对象。

 

1、表示对当前对象的引用!

1
2
3
4
5
public class A{
   public A getA(){
      return this;//表示获取当前实例本身
   }
}

2、表示类的成员变量,而非函数参数,注意在函数参数和成员变量同名是进行区分!

1
2
3
4
5
6
public class A{
   private int a = 0;//位置1
   public A getA(int a){
      this.a = a;//前面this.a表示 位置1 的a,赋值=号右侧的表示参数a
   }
}

3、用于在构造方法中引用满足指定参数类型的构造器。

1
2
3
4
5
6
7
public class A{
   public A(int a){
   }
   public A(){ 
     this(1);//这里调用自身的构造函数public A(int a){
   }
}
posted @ 2017-03-19 21:59  JAVA&up  阅读(128)  评论(0编辑  收藏  举报