非靜態(tài)類
兩者都是非靜態(tài)類可以互相訪問,內(nèi)部類訪問外部類沒有疑問,就像是一個(gè)方法(這里只內(nèi)部類)訪問類中的變量一樣;但是,外部類的成員也可以訪問內(nèi)部類的內(nèi)容,但是親測必須實(shí)例了這個(gè)內(nèi)部類才可以使用(具體原因去查大佬們寫的博客)。
方法外只能對定義的變量賦值,不可對游離變量賦值(功底弱):
錯(cuò)誤示例:
注:突發(fā)奇想那一個(gè)類里面的方法定義的私有變量類可以訪問到嗎,然后發(fā)現(xiàn)方法里不能加權(quán)限作用域。
上代碼:
package?com.it.demo03;?public?class?MyTest1?{?????private?String??s?=?"yyy";??????class?Inner{????????private?String??u?=?"uuu";????????public?Inner(){????????}????????public?void?gets(){????????????System.out.println(s);????????}????}?????public?void?getu()?{?????????Inner?inner?=?new?Inner();????????System.out.println(inner.u);????}}class?Test2{????public?static?void?main(String[]?args)?{????????MyTest1?myTest1?=?new?MyTest1();????????MyTest1.Inner?inner?=?myTest1.new?Inner();????????inner.gets();????????myTest1.getu();????}}
靜態(tài)類:
效果相似:
package?com.it.demo03;public?class?MyTest2?{private?static?String??s?=?"yyy";static?class?Inner{private?static?String??u?=?"uuu";public?Inner(){}public?static?void?gets(){System.out.println(s);s?=?"us";}}public?static?void?getu()?{//????????Inner?inner?=?new?Inner();//????????System.out.println(inner.u);System.out.println(Inner.u);}}class?Test3{public?static?void?main(String[]?args)?{MyTest2.getu();MyTest2.Inner.gets();}}
靜態(tài)內(nèi)部類實(shí)現(xiàn)單例模式:
pacpackage?com.it.demo02;?public?class?SingletonDemo05?{????private?volatile?static?SingletonDemo05?singletonDemo05?=?null;????public?static?void?getsd(){????????System.out.println("getsd:"+singletonDemo05);????}????private?SingletonDemo05(){}????private?static?class?Inner{????????public?static?SingletonDemo05?getSD(){????????????if(singletonDemo05?==?null){????????????????synchronized?(SingletonDemo05.class){????????????????????if?(singletonDemo05?==?null)????????????????????????singletonDemo05?=?new?SingletonDemo05();????????????????}????????????}????????????return?singletonDemo05;????????}????}????public?static?SingletonDemo05?getSingletonDemo05(){????????return?Inner.getSD();????}}?class?Test4{????public?static?void?main(String[]?args)?{????????SingletonDemo05.getsd();????????SingletonDemo05?singletonDemo05?=?SingletonDemo05.getSingletonDemo05();????????SingletonDemo05?singletonDemo051?=?SingletonDemo05.getSingletonDemo05();????????System.out.println(singletonDemo05?==?singletonDemo051);?????????SingletonDemo05.getsd();????????System.out.println(singletonDemo05.hashCode());????????System.out.println(singletonDemo051.hashCode());????}}
以上就是長沙中公優(yōu)就業(yè)java培訓(xùn)機(jī)構(gòu)的小編針對“記錄Java內(nèi)部類的訪問權(quán)限問題”的內(nèi)容進(jìn)行的回答,希望對大家有所幫助,如有疑問,請?jiān)诰€咨詢,有專業(yè)老師隨時(shí)為你服務(wù)。