Java中的內部類使用詳情
更新時間:2022年04月06日 17:09:12 作者:wx60d4764eb475e
說起內部類這個詞,想必很多人都不陌生,但是又會覺得不熟悉。原因是平時編寫代碼時可能用到的場景不多,用得最多的是在有事件監(jiān)聽的情況下,并且即使用到也很少去總結內部類的用法。今天我們就來一探究竟
一,內部類訪問成員
- 1,內部類可以直接訪問外部類的成員,包括私有。
- 2,外部類要訪問內部類,必須建立內部類對象。
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(); } }
二,訪問內部類成員
1,直接訪問內部類的中的成員
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,訪問成員
之所以可以直接訪問外部類的成員,是因為內部類中持有了一個外部類的引用,格式: 外部類名.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(); } }
到此這篇關于Java十分鐘精通內部類的使用的文章就介紹到這了,更多相關Java 內部類內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringCloud Zuul在何種情況下使用Hystrix及問題小結
這篇文章主要介紹了SpringCloud Zuul在何種情況下使用Hystrix 及問題小結,感興趣的朋友跟隨小編一起看看吧2018-11-11