[20-05-16][Thinking in Java 20]Java Inner Class 4 - Nesting a class within a method

时间:2020-05-16
本文章向大家介绍[20-05-16][Thinking in Java 20]Java Inner Class 4 - Nesting a class within a method,主要包括[20-05-16][Thinking in Java 20]Java Inner Class 4 - Nesting a class within a method使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
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

原文地址:https://www.cnblogs.com/mirai3usi9/p/12902230.html