java基础:this关键字

一:使用场景
 

 (1)在一个构造方法中,通过this关键字调用所在类中的另一个构造方法。

(2)在一个实例方法内,局部变量或参数与实例变量名称相同,编译口器无法区分变量,这时要用this关键字。

(3)在一个实例方法内,通过this关键字访问当前实例的引用。

 

二:举例说明

 
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
/**
* this关键字
* (1)出现在方法中
* (2)this代表使用该方法的对象的引用
*
* @author 刘彦亮
* @version 1.0
*/
public class ThisTest {
int i = 0; // 成员变量i
 
// 构造方法 形参i
ThisTest(int i) {
this.i = i;
//未知i就近原则,就是形参
//this.i就是成员变量
}
 
ThisTest increaseMent() {
i++;
return this;
}
void print(){
System.out.println("i="+i);
}
public static void main(String[] args) {
ThisTest test = new ThisTest(100);
test.increaseMent().increaseMent().print();
}
 
}
 来自CODE的代码片
this关键字
 
运行结果: i = 102
posted @ 2016-12-02 21:48  天涯海角路  阅读(96)  评论(0)    收藏  举报