1 //: Parcel4.java 2 3 package cn.skyfffire; 4 5 /** 6 * 7 * @author skyfffire 8 * 9 */ 10 11 public class Parcel4 { 12 /* 定义接口,方便访问,美中不足的是,无法在接口的基础上增加方法。 */ 13 interface Destination { 14 String readLabel(); 15 } 16 17 public static Destination dest(String s) { 18 /* 内部类(置于方法),这样可以做到隐藏类 */ 19 class PDestination implements Destination { 20 private String label; 21 22 public PDestination(String whereTo) { 23 label = whereTo; 24 } 25 26 @Override 27 public String readLabel() { 28 return label; 29 } 30 } 31 32 return new PDestination(s); 33 } 34 35 public static void main(String[] args) { 36 System.out.println(Parcel4.dest("make").readLabel()); 37 } 38 }
也可以使用这种方法构建几乎同效果的内部类:
1 //: Parcel6.java 2 3 package cn.skyfffire; 4 5 public class Parcel6 { 6 interface Contents { 7 int value(); 8 } 9 10 public Contents cont() { 11 return new Contents() { 12 private int i = 11; 13 14 @Override 15 public int value() { 16 return i; 17 } 18 }; 19 } 20 21 public static void main(String[] args) { 22 Parcel6 parcel6 = new Parcel6(); 23 24 Contents c = parcel6.cont(); 25 26 System.out.println(c.value()); 27 } 28 } 29 30 ///: ~
第二种写法比较怪异。