Java內部類(4):靜態內部類&介面內部類

來源:互聯網
上載者:User

標籤:microsoft   other   amp   level   body   this   span   turn   imp   

使用static修飾的內部類我們稱之為靜態內部類,不過我們更喜歡稱之為嵌套內部類。靜態內部類與非靜態內部類之間存在一個最大的區別,我們知道非靜態內部類在編譯完成之後會隱含地儲存著一個引用,該引用是指向建立它的外圍內,但是靜態內部類卻沒有。沒有這個引用就意味著:

1、 它的建立是不需要依賴於外圍類的。

2、 它不能使用任何外圍類的非static成員變數和方法。

 1 interface Contents { 2     int value(); 3 } 4  5 interface Destination { 6     String readLabel(); 7 } 8  9 class Test005Sub {10 11     private static class ParcelContents implements Contents {12         private int i = 11;13 14         public int value() {15             return i;16         }17     }18 19     static class ParcelDestination implements Destination {20         private String s;21 22         private ParcelDestination(String s) {23             this.s = s;24         }25 26         public String readLabel() {27             return s;28         }29 30         public static void f() {31         }32 33         static int x = 10;34 35         static class AnotherLevel {36             {37                 x = 111;38                 System.out.println(x);39             }40         }41     }42 43     public static Contents contents() {44         return new ParcelContents();45     }46 47     public static Destination destination() {48         return new ParcelDestination("Hello World!");49     }50 }51 52 public class Test005 {53     public static void main(String[] args) {54         Contents c = Test005Sub.contents();55         Destination d = Test005Sub.destination();56         new Test005Sub.ParcelDestination.AnotherLevel(); // 11157         System.out.println(c.value()); // 1158         System.out.println(d.readLabel()); // Hello World!59     }60 }

 

還有一种放在介面內的介面內部類

放到介面中的任何類都自動地是public和static的,所以將嵌套類放在介面的命名空間內並不違反介面的規則。

 1 interface Test006Sub { 2  3     void howdy(); 4  5     class Test implements Test006Sub { 6         public void howdy() { 7             System.out.println("howdy!"); 8         } 9     }10 }11 12 public interface Test006 {13     public static void main(String[] args) {14         new Test006Sub.Test().howdy(); // howdy!15     }16 }

 

Java內部類(4):靜態內部類&介面內部類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.