[20-05-17][Thinking in Java 23]Java Inner Class 7 - Anonymous Inner Class 2

1 package test_15_2;
2 
3 public interface Destination {
4 
5     String readLabel();
6 }
 1 package test_15_2;
 2 
 3 public class Outer {
 4 
 5     // 如果定义一个匿名内部类,并希望它使用一个在外部定义的对象,那么引用参数必须是final的,否则编译错误
 6     public Destination destination(final String dest) {
 7 
 8         return new Destination() {
 9 
10             private String label = dest;
11 
12             @Override
13             public String readLabel() {
14 
15                 return label;
16             }
17         };
18     }
19 
20     public static void main(String[] args) {
21 
22         Outer outer = new Outer();
23         Destination d = outer.destination("Persona");
24 
25         System.out.println(d.readLabel());
26 
27     }
28 }

猜你喜欢

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