1 package test_14_2; 2 3 public interface Destination { 4 5 String readLabel(); 6 }
1 package test_14_2; 2 3 public class Parcel { 4 5 public Destination destination(String s) { 6 7 class PDestination implements Destination { 8 private String label; 9 10 private PDestination(String whereTo) { 11 label = whereTo; 12 } 13 14 public String readLabel() { 15 return label; 16 } 17 } 18 return new PDestination(s); 19 } 20 21 public static void main(String[] args) { 22 /* 23 * PDestination是destination()方法的一部分,而不是Parcel的一部分 24 * 所以,在destination()之外不能访问PDestination 25 * 注意出现在return语句中的向上转型——返回的是Destination的引用,它是PDestination的基类 26 * 在destination()中定义了内部类PDestination,并不意味着一旦destination()方法执行完毕,PDestination就不可用了 27 */ 28 Parcel p = new Parcel(); 29 Destination d = p.destination("Joker"); 30 31 System.out.println(d.readLabel()); 32 } 33 }
结果如下:
Joker