Java的Inner Class的实例及作用分析

来源:互联网 发布:剑灵如何导入捏脸数据 编辑:程序博客网 时间:2024/04/29 22:37

 

http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html

1 首先看代码

/*
 * DataStructure.java
 *
 * Created on 2008年3月1日, 上午10:37
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 
*/


package hiber;

/**
 *
 * 
@author rulinma
 
*/

public class DataStructure {
    
//create an array
    private final static int SIZE = 15;
    
private int[] arrayOfInts = new int[SIZE];
    
    
public DataStructure() {
        
//fill the array with ascending integer values
        for (int i = 0; i < SIZE; i++{
            arrayOfInts[i] 
= i;
        }

    }

    
    
public void printEven() {
        
//print out values of even indices of the array
        InnerEvenIterator iterator = this.new InnerEvenIterator();
        
while (iterator.hasNext()) {
            System.out.println(iterator.getNext() 
+ " ");
        }

    }

    
//inner class implements the Iterator pattern
    private class InnerEvenIterator {
        
//start stepping through the array from the beginning
        private int next = 0;
        
        
public boolean hasNext() {
            
//check if a current element is the last in the array
            return (next <= SIZE - 1);
        }

        
        
public int getNext() {
            
//record a value of an even index of the array
            int retValue = arrayOfInts[next];
            
//get the next even element
            next += 2;
            
return retValue;
        }

    }

    
    
public static void main(String s[]) {
        
//fill the array with integer values and print out only values of even indices
        DataStructure ds = new DataStructure();
        ds.printEven();
    }

}



 2 运行结果:

init:
deps-jar:
compile-single:
run-single:
0
2
4
6
8
10
12
14
生成成功(总时间:1 秒)

3 作用分析

  3.1 内部类的使用可以有效避免外界对InnerEvenIterator 类的访问,满足了面向对象的封装性。

  3.2 内部类InnerEvenIterator可以直接使用上面定义的  private int[] arrayOfInts = new int[SIZE];
        Java编译器在创建内部类对象时,隐式的把其外部类对象的引用也传了进去并一直保存着。这样就使得内部类对象始终可以访问其外部类对象

原创粉丝点击