標籤: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):靜態內部類&介面內部類