Java内部类(4):静态内部类&接口内部类

使用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(); // 111
57         System.out.println(c.value()); // 11
58         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 }
原文地址:https://www.cnblogs.com/storml/p/8318182.html