this關鍵字是什麼?
關鍵字this只能在方法內部使用,表示對目前物件的參考。
this關鍵字的用法
1、存取成員變量,區分成員變數和局部變數
2、存取成員方法
3、存取建構方法
4、傳回目前物件的參考
5、將對目前物件的參考作為參數傳遞給其他方法
用法如下: Test0505.java
class Person{ private String name;//成员变量 private int age; Person(){} Person(String name){//局部变量 this.name=name;//1.用"this.成员变量名称"和重名的局部变量区分开来 } 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关键字一般不写,让编译器自动添加。 } } 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()的构造方法 this.name=name; } Person(String name,int age){//在构造方法内调用另一个构造方法 this(name);//3."this();"访问构造方法必须放在构造方法的第一行 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(); } }
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.将对当前对象的引用作为参数传递给其他方法。 } } 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的詳細內容。更多資訊請關注PHP中文網其他相關文章!
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前By尊渡假赌尊渡假赌尊渡假赌
刺客信條陰影:貝殼謎語解決方案
2 週前ByDDD
R.E.P.O.如果您聽不到任何人,如何修復音頻
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Atom編輯器mac版下載
最受歡迎的的開源編輯器

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

WebStorm Mac版
好用的JavaScript開發工具