標籤:seq 構建 執行個體化 i++ main string object oid pre
通過內部類實現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內部類