带参数的匿名类初始化——《Thinking in Java》随笔020

 1 //: Parcel8.java
 2 
 3 package cn.skyfffire;
 4 
 5 interface Destination {
 6     String readLabel();
 7 }
 8 
 9 public class Parcel8 {
10     public static Destination dest(final String dest) {
11         return new Destination() {
12             String label = dest;
13             
14             @Override
15             public String readLabel() {
16                 return label;
17             }
18         };
19     }
20     
21     public static void main(String[] args) {
22         System.out.println(Parcel8.dest("heiheihei").readLabel());
23     }
24 }
25 
26 ///: ~

 也可以使用第二种方法:

 1 //: Parcel9.java
 2 
 3 package cn.skyfffire;
 4 
 5 public class Parcel9 {
 6     interface Destination {
 7         String readLabel();
 8     }
 9     
10     public Destination dest(final String dest, 
11             final int price) {
12         return new Destination() {
13             private int cost;
14             private String label;
15             
16             // 直接通过构造代码块进行初始化
17             {
18                 label = dest;
19                 cost = price;
20             }
21             
22             @Override
23             public String readLabel() {
24                 return label + ":" + cost;
25             }
26         };
27     }
28 }
29 
30 ///: ~
原文地址:https://www.cnblogs.com/skyfffire/p/6492201.html