新聞中心
這篇文章將為大家詳細(xì)講解有關(guān)java中this關(guān)鍵字的用法,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。
成都創(chuàng)新互聯(lián)是一家集網(wǎng)站建設(shè),烏當(dāng)企業(yè)網(wǎng)站建設(shè),烏當(dāng)品牌網(wǎng)站建設(shè),網(wǎng)站定制,烏當(dāng)網(wǎng)站建設(shè)報價,網(wǎng)絡(luò)營銷,網(wǎng)絡(luò)優(yōu)化,烏當(dāng)網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強企業(yè)競爭力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時我們時刻保持專業(yè)、時尚、前沿,時刻以成就客戶成長自我,堅持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實用型網(wǎng)站。
this關(guān)鍵字是什么?
關(guān)鍵字this只能在方法內(nèi)部使用,表示對當(dāng)前對象的引用。
this關(guān)鍵字的用法
1、訪問成員變量,區(qū)分成員變量和局部變量
2、訪問成員方法
3、訪問構(gòu)造方法
4、返回對當(dāng)前對象的引用
5、將對當(dāng)前對象的引用作為參數(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)鍵字一般不寫,讓編譯器自動添加。 } } 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ò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.返回對當(dāng)前對象的引用。 } 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);//輸出對當(dāng)前對象的引用。 return Peeler.peel(this);//5.將對當(dāng)前對象的引用作為參數(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); } }
關(guān)于java中this關(guān)鍵字的用法就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
本文名稱:java中this關(guān)鍵字的用法
當(dāng)前路徑:http://fisionsoft.com.cn/article/jdhdic.html