筆記匯總:《Java面向?qū)ο蟪绦蛟O(shè)計》學(xué)習(xí)筆記
用static修飾內(nèi)部類,可以直接通過內(nèi)部類類名訪問靜態(tài)內(nèi)部類。
public class StaticTest {
//static關(guān)鍵字修飾內(nèi)部類
public static class InnerClass{
InnerClass(){
System.out.println("====== 靜態(tài)內(nèi)部類 ======");
}
public void InnerMethod() {
System.out.println("===== 靜態(tài)內(nèi)部方法 =====");
}
}
public static void main(String[] args) {
//直接通過StaticTest類名訪問靜態(tài)內(nèi)部類InnerClass
InnerClass inner=new StaticTest.InnerClass();
//靜態(tài)內(nèi)部類可以和普通類一樣使用
inner.InnerMethod();
}
}
沒有用static修飾內(nèi)部類,則需要new一個外部類實例,再通過外部實例創(chuàng)建內(nèi)部類。
public class StaticTest {
//無static關(guān)鍵字修飾內(nèi)部類
public class NoClass{
NoClass(){
System.out.println("== 靜態(tài)內(nèi)部類==");
}
public void NoMethod() {
System.out.println("== 內(nèi)部方法 ==");
}
}
public static void main(String[] args) {
//無static時,new一個外部類實例。再通過外部實例創(chuàng)建內(nèi)部類
//1.分開寫
StaticTest st = new StaticTest();
//<外部類類名>.<內(nèi)部類類名> 引用變量 = <外部類構(gòu)造器>.new <內(nèi)部類構(gòu)造器>;
StaticTest.NoClass no = st.new NoClass();
no.NoMethod();
//2.合在一起寫
//new外部類實例并同時創(chuàng)建其內(nèi)部類
StaticTest.NoClass no1 = new StaticTest().new NoClass();
no1.NoMethod();
}
}
外部類之外創(chuàng)建內(nèi)部類對象_new關(guān)鍵字通過外部類創(chuàng)建內(nèi)部類對象_Dingwensheng1222的博客-CSDN博客文章來源:http://www.zghlxwxcb.cn/news/detail-626659.html
?Java 里的static是干嘛的? - 知乎文章來源地址http://www.zghlxwxcb.cn/news/detail-626659.html
到了這里,關(guān)于靜態(tài)內(nèi)部類的訪問方法(static/無static)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!