[20-05-16][Thinking in Java 19]Java Inner Class 3 - Inner Class & Upcasting

1 package test_14_1;
2 
3 public interface Destination {
4 
5     String readLabel();
6     
7 }
1 package test_14_1;
2 
3 public interface Contents {
4 
5     int value();
6 }
 1 package test_14_1;
 2 
 3 public class Pracel {
 4 
 5     private class PContents implements Contents {
 6 
 7         private int i = 1;
 8 
 9         @Override
10         public int value() {
11 
12             return i;
13         }
14 
15     }
16 
17     protected class PDestination implements Destination {
18 
19         private String label;
20 
21         public PDestination(String whereTo) {
22 
23             label = whereTo;
24         }
25 
26         @Override
27         public String readLabel() {
28 
29             return label;
30         }
31     }
32 
33     public Destination destination(String s) {
34 
35         return new PDestination(s);
36     }
37 
38     public Contents contents() {
39 
40         return new PContents();
41     }
42 
43 }
 1 package test_14_1;
 2 
 3 public class Test {
 4 
 5     public static void main(String[] args) {
 6 
 7         /*
 8          * private内部类给类的设计者提供了一种途径,通过这种方式可以完全阻止任何依赖于类型的编码
 9          * 并完全隐藏了实现的细节
10          * 从客户端程序员的角度看,由于不能访问任何新增加的、原本不属于公共接口的方法
11          * 所以扩展接口是没有价值的
12          */
13         Pracel pracel = new Pracel();
14         Contents contents = pracel.contents();
15         Destination destination = pracel.destination("str");
16         
17         System.out.println(contents.value());
18         System.out.println(destination.readLabel());
19     }
20 
21 }

结果如下:

1
str

猜你喜欢

转载自www.cnblogs.com/mirai3usi9/p/12898053.html