zoukankan      html  css  js  c++  java
  • Java中的Inner Class (一)

    Inner Class看起来是一个简单的Code-Hideing机制,但是Java的Inner Class和C++的有所不同 - Inner Class能够和外部类(Surrounding Class)直接打交道,而无任何限制。

    当你创建一个内部类对象的时候,这个对象会保持同外部对象(the object of surrounding class)的联系,这样内部类对象可以自由的访问外部类对象的成员,没有任何限制。比如:

    // 接口定义

    interface Selector{

      boolean end();

      Object current();

      void next();

    }

    // Sequence class

    public class Sequence{

      private Object[] items;

      private int next = 0;

      public Sequence(int size){ items = new Object[size]; }

      pubic void add(Object x){

        if (next < items.length)

          items[next++] = x;

      }

      // 内部类实现Selector接口。

      private class SequenceSelector impements Selector{

        private int i = 0;

        public boolean end() {return i == items.length;} //直接使用Sequence的成员。

        Object current() { return items[i]; }

        public void next() { if (i < items.length) i++; }

      }

      // 将内部类实现以Selector接口形式暴露出来。

      public Selector getSelector() { return new SequenceSelector(); }

      // 测试代码

      public static void main(String[] args){

        Sequence sequence = new Sequence(10);

        for (int i  = 0; i < 10; i++) sequence.add(Integer.toString(i));

        Selector selector = sequence.getSelector();

        while(!selector.end()){

          System.out.print(selector.current() + " ");

          selector.next();

        }

      }

    }

    //输出

    0 1 2 3 4 5 6 7 8 9

    从上面的代码中可以看出,inner class是一种非常好的隐藏代码的设计模式 - 而且非常方便,不必为out class和Inner class直接的交流而操心。

  • 相关阅读:
    git .gitignore不生效的解决方法
    python 爬虫中常需要睡眠防止被封IP time sleep
    Python 实现字典操作详解
    Python遍历字典到列表中出现覆盖前面数据或者字典对值(值为列表)赋值出现重复的问题
    小红书app之shield 逆向
    淘宝h5 页面 sign加密算法
    jemter-base64加密
    Python 中更优雅的日志记录方案
    logging再学习
    elasticsearch中must和should条件同时满足
  • 原文地址:https://www.cnblogs.com/AllanDragoon/p/3251924.html
Copyright © 2011-2022 走看看