2012-11-11 121 views
2

我想從我的超類創建一個子類的新實例。這是我的超級類Java:在靜態方法中從超類創建一個子類的實例

public abstract class Worker { 

    String world; 

    protected abstract void onLoad(Scanner read); 

    public static Worker load(Scanner read) { 
     // I want to create the instance of my sub class here and call it w 
     w.onLoad(read); 
     return w; 
    } 

    public void setWorld(String world) { 
     this.world = world; 
    } 

} 

這是我的子類

public class Factory extends Worker { 

    @Override 
    protected onLoad(Scanner read) { 
     setWorld(read.readline()); 
    } 

} 

而這就是我想和這些類的事情。

public class MainClass{ 

    public List<Factory> loadFactories() { 
     List<Factory> facts = new ArrayList<Factory>(); 
     Scanner read = new Scanner(new FileInputStream("factory.txt")); 

     while(read.hasNextLine()) { 
      Factory f = (Factory)Factory.load(read); 
      facts.add(f); 
     } 

     read.close(); 
     return facts; 
    } 

} 

有什麼辦法可以做到這一點,而不必重新開始?謝謝你的幫助。

+0

您還沒有作出'Worker'一個子類呢。 –

+2

如果你想讓Factory成爲Worker的一個子類,一個好的開始是編寫:'class Factory extends Worker'。 – assylias

+0

什麼在factory.txt? –

回答

2

這是你想要的嗎?

public static Worker load(Scanner read) { 
    Factory w=new Factory(); 
    w.onLoad(read); 
    return w; 
} 

編輯:

public class MainClass { 

    public List<Factory> loadFactories() throws FileNotFoundException, InstantiationException, IllegalAccessException { 
     final List<Factory> facts = new ArrayList<Factory>(); 
     final Scanner read = new Scanner(new FileInputStream("factory.txt")); 

     while (read.hasNextLine()) { 
      final Factory f = Worker.load(read, Factory.class); 
      facts.add(f); 
      final Pipeline p = Worker.load(read, Pipeline.class); 
     } 

     read.close(); 
     return facts; 
    } 

    static public class Factory extends Worker { 

     @Override 
     protected void onLoad(final Scanner read) { 

     } 

    } 

    static public class Pipeline extends Worker { 

     @Override 
     protected void onLoad(final Scanner read) { 

     } 

    } 

    static public abstract class Worker { 

     String world; 

     protected abstract void onLoad(Scanner read); 

     public static <T extends Worker> T load(final Scanner read, final Class<T> t) throws InstantiationException, IllegalAccessException { 
      final T w = t.newInstance(); 
      w.onLoad(read); 
      return w; 
     } 

     public void setWorld(final String world) { 
      this.world = world; 
     } 

    } 
} 
+1

不知道爲什麼這是被拒絕投票 - 這是唯一的答案,如果你面對的價值問題! –

+0

對我來說,它看起來像一個工廠設計模式的完美例子!我不可能用另一種方式解釋它。當然主要的方法應該是Worker f = Worker.load(read); – thedayofcondor

+0

是的,但不完全一樣。假設我有另一個名爲Pipeline的Worker類,並且我想告訴它是Pipeline還是Factory(沒有枚舉)。 – ChrisixStudios

相關問題