Java內部類

來源:互聯網
上載者:User

標籤:new   靜態內部類   pre   調用   interface   java內部類   直接   外部類   依賴   

什麼是內部類?

放在一個類的內部的類,我們稱之為內部類

 

為什麼使用內部類?

1.內部類提供了更好的封裝,只有外部類才可以直接存取內部類。

2.內部類可以繼承和實現介面,不收外部類的影響。

3.內部類的方法和屬性即使是外部類也不能直接存取,而內部類卻可以隨時訪問外部類的屬性和方法。

4.有利於回呼函數的編寫

 

Java內部類共分為4種

成員內部類

方法(局部)內部類

匿名內部類

靜態內部類

 

使用方法

 

成員內部類

/** * 成員內部類 * 1.不能有static修飾的變數和方法,如果有必須加上final修飾 * 2.成員內部類是依附外部類的,只有建立外部類才能建立內部類 * 3.外部類不能直接存取內部類的屬性和方法,需要一個內部類的一個執行個體來訪問 *  * @author Administrator * */public class Outer {private int num=5;class Inner{private int num=10;public void print(){//調用內部類變數System.out.println("內部類方法"+num);//調用外部類變數System.out.println("外部類方法"+Outer.this.num);}}public void print(){System.out.println("外部類方法");}public static void main(String[] args) {
          //方式一//建立外部類對象Outer out=new Outer();//建立內部類對象Inner inner = out.new Inner();inner.print();//外部類方法out.print();
//方式二//建立內部類對象Outer.Inner in=new Outer().new Inner();//調用內部類方法in.print();}}

  

方法(局部)內部類

/** * 方法內部類 * 1.不可以有靜態變數 * 2.只能調用方法內的常量 * 3.不能有存取修飾詞 * @author Administrator * */public class Outer1 {public void print(){final int nums=5;class Inner{private int num=10;public void print(){System.out.println("內部類方法變數"+this.num);//調用方法內變數System.out.println("外部類方法變數"+nums);}}//調用內部類方法new Inner().print();}public static void main(String[] args) {new Outer1().print();}}

  

匿名內部類

/** * 匿名內部類 * 1.必須繼承一個抽象類別或介面 * 2.不能有static修飾的成員變數和方法,只能用final修飾 * 3.所在方法內變數都必須使用final修飾 * 4.沒有存取修飾詞 * 5.沒有構造,因為他沒有類名 * @author Administrator * */public class Outer2 {private int num=5;public void print(){final int num=10;new Inner(){public void print() {System.out.println("外部類"+Outer2.this.num);System.out.println("內部類"+num);}}.print();}//定義一個介面interface Inner{void print();}public static void main(String[] args) {new Outer2().print();}}

  

靜態內部類

/** * 靜態內部類 * 1.不需要依賴外部類,可以直接建立 * 2.靜態內部類不能使用外部類的非靜態成員和方法,而內部類可以 * 3.不能使用   外部類名.this.屬性名稱/方法 * @author Administrator * */public class Outer3 {private static int nums=5;//建立靜態內部類static class Inner{private int num=10;public void print(){System.out.println("內部類"+num);System.out.println("外部類"+nums);}}public static void main(String[] args) {Inner in=new Inner();in.print();}}

  

 

Java內部類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.