内部类自动拥有对外围类所有成员的访问权

    1. interface Selector{
    2. boolean end();
    3. Object current();
    4. void next();
    5. }
    6. public class Sequence {
    7. private Object[] items;
    8. private int next = 0;
    9. public Sequence(int size){
    10. items = new Object[size];
    11. }
    12. public void add(Object x){
    13. if (next < items.length){
    14. items[next++] = x;
    15. }
    16. }
    17. private class SequenceSelector implements Selector{
    18. private int i = 0;
    19. @Override
    20. public boolean end() {
    21. return i==items.length;
    22. }
    23. @Override
    24. public Object current() {
    25. return items[i];
    26. }
    27. @Override
    28. public void next() {
    29. if (i<items.length){
    30. i++;
    31. }
    32. }
    33. }
    34. public Selector selector(){
    35. return new SequenceSelector();
    36. }
    37. public static void main(String[] args) {
    38. Sequence s = new Sequence(5);
    39. for (int i = 0; i<5 ; i++){
    40. s.add(Integer.toString(i));
    41. }
    42. Selector selector = s.selector();
    43. while (!selector.end()){
    44. System.out.println(selector.current()+" ");
    45. selector.next();
    46. }
    47. }
    48. }
    49. 输出: 0 1 2 3 4