this 有三個(gè)作用:
- 使用this調(diào)用本類的成員變量
public class ThisDemo {
private String name = "coco";
public void print(String name){
System.out.println(this.name);
System.out.println(name); //就近原則
}
public static void main(String[] args) {
ThisDemo t = new ThisDemo();
t.print("xing");
}
}
運(yùn)行結(jié)果:
coco
xing
- 調(diào)用本類中的其他方法
public class ThisDemo {
private String name = "coco";
public void setName(String name) {
this.name = name;
this.print();
}
public void print() {
System.out.println("*****");
}
public String getName() {
return this.name;
}
public static void main(String args[]) {
ThisDemo t = new ThisDemo();
t.setName("xingxing");
System.out.println(t.getName());
}
}
package coco.perm;
public class ThisDemo {
private int i=0;
//第一個(gè)構(gòu)造器:有一個(gè)int型形參
ThisDemo(int i){
this.i=i;//此時(shí)this表示引用成員變量i赏廓,而非函數(shù)參數(shù)i
System.out.println(this.i);
System.out.println(this.i+1);
//從兩個(gè)輸出結(jié)果充分證明了i和this.i是不一樣的想许!
}
// 第二個(gè)構(gòu)造器:有一個(gè)String型形參
ThisDemo(String s){
System.out.println(s);
}
// 第三個(gè)構(gòu)造器:有一個(gè)int型形參和一個(gè)String型形參
ThisDemo(int i,String s){
this(s);//this調(diào)用第二個(gè)構(gòu)造器
//this(i);
/*此處不能用泼差,因?yàn)槠渌魏畏椒ǘ疾荒苷{(diào)用構(gòu)造器椭盏,只有構(gòu)造方法能調(diào)用他徘层。
但是必須注意:就算是構(gòu)造方法調(diào)用構(gòu)造器峻呕,也必須為于其第一行,構(gòu)造方法也只能調(diào)
用一個(gè)且僅一次構(gòu)造器趣效!*/
// this.i=i++;//this以引用該類的成員變量
//System.out.println(s);
}
public ThisDemo increment(){
this.i++;
return this;//返回的是當(dāng)前的對(duì)象瘦癌,該對(duì)象屬于(ThisTest)
}
public static void main(String[] args){
ThisDemo tt0=new ThisDemo(10);
ThisDemo tt1=new ThisDemo("ok");
ThisDemo tt2=new ThisDemo(20,"ok again!");
System.out.println(tt0.increment().increment().increment().i);
//tt0.increment()返回一個(gè)在tt0基礎(chǔ)上i++的ThisTest對(duì)象,
//接著又返回在上面返回的對(duì)象基礎(chǔ)上i++的ThisTest對(duì)象跷敬!
}
}
- 調(diào)用構(gòu)造方法
public class ThisDemo {
public ThisDemo(){
this("調(diào)用有參構(gòu)造方法");
System.out.println("無(wú)參構(gòu)造方法");
}
public ThisDemo(String name){
System.out.println("有參構(gòu)造方法");
}
}
注意:
- 在類里面讯私,引用這個(gè)類的屬性和方法。
這句代碼在那個(gè)類里面干花,就代表那個(gè)類的對(duì)象妄帘。 -
this
和supper
關(guān)鍵字是非靜態(tài)關(guān)鍵字,不能在main
方法里面