Java中的內(nèi)部類使用詳情
一,內(nèi)部類訪問成員
- 1,內(nèi)部類可以直接訪問外部類的成員,包括私有。
- 2,外部類要訪問內(nèi)部類,必須建立內(nèi)部類對(duì)象。
class Outer { int x = 3; class Inner{ void function(){ System.out.println("inner : " + x); } } void method(){ Inner in = new Inner(); in.function(); } } class InnerClassDome { public static void main (String[] args) { Outer out = new Outer(); out.method(); } }
二,訪問內(nèi)部類成員
1,直接訪問內(nèi)部類的中的成員
class Outer { int x = 3; class Inner{ void function(){ System.out.println("inner : " + x); } } void method(){ Inner in = new Inner(); in.function(); } } class InnerClassDome { public static void main (String[] args) { //Outer out = new Outer(); //out.method(); Outer.Inner in = new Outer().new Inner(); in.function(); } }
2,訪問成員
之所以可以直接訪問外部類的成員,是因?yàn)閮?nèi)部類中持有了一個(gè)外部類的引用,格式: 外部類名.this
class Outer { int x = 3; class Inner{ int x = 4; void function(){ int x = 6; System.out.println("inner : " + x); System.out.println("inner : " + this.x); System.out.println("inner : " + Outer.this.x); } } void method(){ Inner in = new Inner(); in.function(); } } class InnerClassDome { public static void main (String[] args) { //Outer out = new Outer(); //out.method(); Outer.Inner in = new Outer().new Inner(); in.function(); } }
到此這篇關(guān)于Java十分鐘精通內(nèi)部類的使用的文章就介紹到這了,更多相關(guān)Java 內(nèi)部類內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
非常適合新手學(xué)生的Java線程池超詳細(xì)分析
作者是一個(gè)來(lái)自河源的大三在校生,以下筆記都是作者自學(xué)之路的一些淺薄經(jīng)驗(yàn),如有錯(cuò)誤請(qǐng)指正,將來(lái)會(huì)不斷的完善筆記,幫助更多的Java愛好者入門2022-03-03Java案例使用比較排序器comparator實(shí)現(xiàn)成績(jī)排序
這篇文章主要介紹了Java案例使用比較排序器comparator實(shí)現(xiàn)成績(jī)排序,主要通過案例用TreeSet集合存儲(chǔ)多個(gè)學(xué)生信息,并遍歷該集合,要按照總分從高到低進(jìn)行排序,下文介紹需要的朋友可以參考一下2022-04-04SpringCloud Zuul在何種情況下使用Hystrix及問題小結(jié)
這篇文章主要介紹了SpringCloud Zuul在何種情況下使用Hystrix 及問題小結(jié),感興趣的朋友跟隨小編一起看看吧2018-11-11Jackson忽略字段實(shí)現(xiàn)對(duì)字段進(jìn)行序列化和反序列化
在使用?Jackson?進(jìn)行序列化和反序列化時(shí),有時(shí)候需要對(duì)某些字段進(jìn)行過濾,以便在?JSON?數(shù)據(jù)中不包含某些敏感信息,下面就一起來(lái)了解一下Jackson忽略字段實(shí)現(xiàn)對(duì)字段進(jìn)行序列化和反序2023-10-10使用session實(shí)現(xiàn)簡(jiǎn)易購(gòu)物車功能
這篇文章主要為大家詳細(xì)介紹了使用session實(shí)現(xiàn)簡(jiǎn)易購(gòu)物車功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02