什么是this?
this是自身的一個對象,代表對象本身,可以理解為:指向?qū)ο蟊旧淼囊粋€指針。
用法如下:
用"this.成員變量名稱"和重名的局部變量區(qū)分開來;
用"this.成員方法名"訪問成員方法。
立即學習“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(); } }
this()訪問構(gòu)造方法必須放在構(gòu)造方法的第一行
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.返回對當前對象的引用。 } 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(); } }
將對當前對象的引用作為參數(shù)傳遞給其他方法
class Person{ void eat(Apple apple){ Apple peeled=apple.getPeeled(); System.out.println(peeled); } } class Apple{ Apple getPeeled(){ System.out.println(this);//輸出對當前對象的引用。 return Peeler.peel(this);//5.將對當前對象的引用作為參數(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教程
以上就是java中的this關(guān)鍵字是什么意思的詳細內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
java怎么學習?java怎么入門?java在哪學?java怎么學才快?不用擔心,這里為大家提供了java速學教程(入門到精通),有需要的小伙伴保存下載就能學習啦!
微信掃碼
關(guān)注PHP中文網(wǎng)服務號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://www.miracleart.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號