首页 > 代码库 > Java内部类

Java内部类

通过内部类实现Sequence

public class test {

    private Object []obj;
    private int next = 0 ;
    
    test(int i){
        obj = new Object[i];
    }
    
    public void addObject(Object j){
        obj[next++] = j;
    }
    
    int getLength(){
        return obj.length;
    }
    public class inerObject {
        private int i=0;
        public boolean end(){
            return i==obj.length;
        }
        public Object current(){
            if(i>=obj.length)
                return null;
            else 
                return obj[i];
        }
        public Object next(){
            if(obj.length==0||i>=obj.length){
                System.out.print("i is : "+i+"    ");
                return null;
            }
                
            else {
                System.out.print("i is : "+i+"    ");
            }
                return obj[++i];
        }
    }

    
    public  static void main(String []args){
        test t = new test(10);
        for(int i=0;i<t.getLength();i++){
            t.addObject(Integer.toString(i));
        }
        inerObject ir = t.new inerObject();
        while(!ir.end()){
            System.out.println(ir.next());
        }
    }
}

在Main中构建 内部类时必须有一个 外部类的对象,否者不能实例化

         inerObject ir = t.new inerObject();
因为构建内部类对象时,需要一个指向其外部类对象的引用,如果编译器访问不到这个引用时就会报错。(static除外)



Java内部类