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直接的交流而操心。

转载于:https://www.cnblogs.com/AllanDragoon/p/3251924.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值