您好,登錄后才能下訂單哦!
這篇文章主要講解了“Java中this方法如何使用”,文中的講解內(nèi)容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Java中this方法如何使用”吧!
1.this的類型:哪個對象調(diào)用就是哪個對象的引用類型
1.this.data; //訪問屬性
2.this.func(); //訪問方法
3.this(); //調(diào)用本類中其他構(gòu)造方法
這種是在成員方法中使用
讓我們來看看不加this會出現(xiàn)什么樣的狀況
class MyDate{ public int year; public int month; public int day; public void setDate(int year, int month,int day){ year = year;//這里沒有加this month = month;//這里沒有加this day = day;//這里沒有加this } public void PrintDate(){ System.out.println(year+"年 "+month+"月 "+day+"日 "); } } public class TestDemo { public static void main(String[] args) { MyDate myDate = new MyDate(); myDate.setDate(2000,9,25); myDate.PrintDate(); MyDate myDate1 = new MyDate(); myDate1.setDate(2002,7,14); myDate1.PrintDate(); } }
我們想要達到的預(yù)期是分別輸出2000年9月25日,2002年7月14日。
而實際輸出的結(jié)果是
而當我們加上this時
class MyDate{ public int year; public int month; public int day; public void setDate(int year, int month,int day){ this.year = year; this.month = month; this.day = day; } public void PrintDate(){ System.out.println(this.year+"年 "+this.month+"月 "+this.day+"日 "); } } public class TestDemo { public static void main(String[] args) { MyDate myDate = new MyDate(); myDate.setDate(2000,9,25); myDate.PrintDate(); MyDate myDate1 = new MyDate(); myDate1.setDate(2002,7,14); myDate1.PrintDate(); } }
就實現(xiàn)了賦值的功能,為了避免出現(xiàn)差錯,我們建議盡量帶上this
這種是指在普通成員方法中使用this調(diào)用另一個成員方法
class Student{ public String name; public void doClass(){ System.out.println(name+"上課"); this.doHomeWork(); } public void doHomeWork(){ System.out.println(name+"正在寫作業(yè)"); } } public class TestDemo2 { public static void main(String[] args) { Student student = new Student(); student.name = "小明"; student.doClass(); } }
運行結(jié)果:
(3)this()
這種指在構(gòu)造方法中使用this調(diào)用本類其他的構(gòu)造方法
這種this的使用注意以下幾點
1.this只能在構(gòu)造方法中調(diào)用其他構(gòu)造方法
2.this要放在第一行
3.一個構(gòu)造方法中只能調(diào)用一個構(gòu)造方法
運行結(jié)果
感謝各位的閱讀,以上就是“Java中this方法如何使用”的內(nèi)容了,經(jīng)過本文的學習后,相信大家對Java中this方法如何使用這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。