zoukankan      html  css  js  c++  java
  • 作用域型内部类的特殊用法——《Thinking in Java》随笔019

     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 ///: ~

    第二种写法比较怪异。

  • 相关阅读:
    数据库底层索引
    shell脚本
    备份还原ESXi 中的虚拟机快照
    docker proxy
    yum
    ubuntu系统更换源和apt命令参数
    前端BootStrap框架和django创建项目和app
    python之路5:常用模块
    python之路3:文件操作和函数基础
    python之路4:各种器
  • 原文地址:https://www.cnblogs.com/skyfffire/p/6492117.html
Copyright © 2011-2022 走看看