this關(guān)鍵字是什么?
關(guān)鍵字this只能在方法內(nèi)部使用,表示對(duì)當(dāng)前對(duì)象的引用。
this關(guān)鍵字的用法
1、訪問成員變量,區(qū)分成員變量和局部變量
2、訪問成員方法
3、訪問構(gòu)造方法
4、返回對(duì)當(dāng)前對(duì)象的引用
5、將對(duì)當(dāng)前對(duì)象的引用作為參數(shù)傳遞給其他方法
用法如下:Test0505.java
class Person{ private String name;//成員變量 private int age; Person(){} Person(String name){//局部變量 this.name=name;//1.用"this.成員變量名稱"和重名的局部變量區(qū)分開來 } Person(String name,int age){ this(name); this.age=age; } String getInfo(){//成員方法 return "姓名:" + name + "n年齡:" + age; } void print(){ System.out.println(this.getInfo());//2.用"this.成員方法名"訪問成員方法。 System.out.println(getInfo());//這種情況this關(guān)鍵字一般不寫,讓編譯器自動(dòng)添加。 } } public class Test0505{ public static void main(String[] args){ Person p=new Person("張三",33); p.print(); } }
class Person{ private String name; private int age; Person(){} Person(String name){//不含this()的構(gòu)造方法 this.name=name; } Person(String name,int age){//在構(gòu)造方法內(nèi)調(diào)用另一個(gè)構(gòu)造方法 this(name);//3."this();"訪問構(gòu)造方法必須放在構(gòu)造方法的第一行 this.age=age; } String getInfo(){ return "姓名:" + name + "n年齡:" + age; } void print(){ System.out.println(this.getInfo()); } } public class Test0505{ public static void main(String[] args){ Person p=new Person("張三",33); p.print(); } }
class Leaf{ private int i=0; Leaf increment(){ i++; return this;//4.返回對(duì)當(dāng)前對(duì)象的引用。 } void print(){ System.out.println("i="+i); } } public class Test0505{ public static void main(String[] args){ Leaf x=new Leaf(); x.increment().increment().increment().print(); } }
class Person{ void eat(Apple apple){ Apple peeled=apple.getPeeled(); System.out.println(peeled); } } class Apple{ Apple getPeeled(){ System.out.println(this);//輸出對(duì)當(dāng)前對(duì)象的引用。 return Peeler.peel(this);//5.將對(duì)當(dāng)前對(duì)象的引用作為參數(shù)傳遞給其他方法。 } } class Peeler{ static Apple peel(Apple apple){ return apple; } } public class Test0505{ public static void main(String[] args){ Apple a=new Apple(); System.out.println(a); new Person().eat(a); } }
推薦教程:java快速入門