Java中this的用法實(shí)例總結(jié)
一、this關(guān)鍵字
1.this的類(lèi)型:哪個(gè)對(duì)象調(diào)用就是哪個(gè)對(duì)象的引用類(lèi)型
二、用法總結(jié)
1.this.data; //訪問(wèn)屬性
2.this.func(); //訪問(wèn)方法
3.this(); //調(diào)用本類(lèi)中其他構(gòu)造方法
三、解釋用法
1.this.data
這種是在成員方法中使用
讓我們來(lái)看看不加this會(huì)出現(xiàn)什么樣的狀況
class MyDate{ public int year; public int month; public int day; public void setDate(int year, int month,int day){ year = year;//這里沒(méi)有加this month = month;//這里沒(méi)有加this day = day;//這里沒(méi)有加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(); } }
我們想要達(dá)到的預(yù)期是分別輸出2000年9月25日,2002年7月14日。
而實(shí)際輸出的結(jié)果是
而當(dāng)我們加上this時(shí)
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(); } }
就實(shí)現(xiàn)了賦值的功能,為了避免出現(xiàn)差錯(cuò),我們建議盡量帶上this
2.this.func()
這種是指在普通成員方法中使用this調(diào)用另一個(gè)成員方法
class Student{ public String name; public void doClass(){ System.out.println(name+"上課"); this.doHomeWork(); } public void doHomeWork(){ System.out.println(name+"正在寫(xiě)作業(yè)"); } } public class TestDemo2 { public static void main(String[] args) { Student student = new Student(); student.name = "小明"; student.doClass(); } }
運(yùn)行結(jié)果:
(3)this()
這種指在構(gòu)造方法中使用this調(diào)用本類(lèi)其他的構(gòu)造方法
這種this的使用注意以下幾點(diǎn)
1.this只能在構(gòu)造方法中調(diào)用其他構(gòu)造方法
2.this要放在第一行
3.一個(gè)構(gòu)造方法中只能調(diào)用一個(gè)構(gòu)造方法
運(yùn)行結(jié)果
總結(jié)
到此這篇關(guān)于Java中this用法總結(jié)的文章就介紹到這了,更多相關(guān)Java中this用法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java 注解實(shí)現(xiàn)一個(gè)可配置線程池的方法示例
這篇文章主要介紹了java 注解實(shí)現(xiàn)一個(gè)可配置線程池的方法示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-01-01JavaWeb實(shí)現(xiàn)簡(jiǎn)單用戶發(fā)送郵件
這篇文章主要為大家詳細(xì)介紹了JavaWeb實(shí)現(xiàn)簡(jiǎn)單用戶發(fā)送郵件,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08SpringBoot如何進(jìn)行業(yè)務(wù)校驗(yàn)實(shí)例詳解
這篇文章主要給大家介紹了關(guān)于SpringBoot如何進(jìn)行業(yè)務(wù)校驗(yàn)的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2022-01-01當(dāng)mybatis返回值遇見(jiàn)內(nèi)部類(lèi)的問(wèn)題
這篇文章主要介紹了當(dāng)mybatis返回值遇見(jiàn)內(nèi)部類(lèi)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12