2017-01-12 170 views
0

嗯,你好,這是我的問題。更改屬性ArrayList <Class>到ArrayList <SubClass>在子類

我想知道,如果給定一個abstract class Foo,有可能,不知何故,得到它的屬性ArrayList<Bar>(酒吧是抽象的也行)只包含它所使用的Foo每個子類中含有一定特定的子類。

例如,在一個具體的該class FooChildextends Foo,屬性ArrayList<Bar>將現在僅包含具體class BarChild(其extends Bar)。

更具體地說,如果我有這段代碼:

public abstract class CharactersGroup { 
    private ArrayList<Character> characters; 

    public CharactersGroup() { 
     this(new ArrayList<Character>()); 
    } 

    public CharactersGroup(ArrayList<Character> list) { 
     characters = list; 
    } 
} 

CharactersGroup一個子類是HeroesGroup,像這樣:

public class HeroesGroup extends CharactersGroup { 
    // Here is an ArrayList<Character> characters, that I would like to "become" an ArrayList<Hero> characters 

    public HeroesGroup() { 
     this(new ArrayList<Hero>()); 
    } 

    public HeroesGroup(ArrayList<Hero> list) { 
     super(list); 
    } 
} 

一個Character將只是想:

And a Hero like:

public class Hero extends Character { 
    private int level; 

    public Hero(String n, int l) { 
     super(n); 
     level = l; 
    } 
} 

回答

0

你可以讓你的抽象類CharactersGroup通用。

public abstract class CharactersGroup<C extends Character> { 
    private ArrayList<C> characters; 

    public CharactersGroup() { 
     this(new ArrayList<C>()); 
    } 

    public CharactersGroup(ArrayList<C> list) { 
     characters = list; 
    } 
} 

子類是這樣的:

public class HeroesGroup extends CharactersGroup<Hero> { 

    public HeroesGroup() { 
     this(new ArrayList<Hero>()); 
    } 

    public HeroesGroup(ArrayList<Hero> list) { 
     super(list); 
    } 
} 
0

使用在超通用參數:

public abstract class CharactersGroup<C extends Character> { 
    private ArrayList<C extends Character> characters; 

    public CharactersGroup() { 
     this(new ArrayList<C extends Character>()); 
    } 

    public CharactersGroup(ArrayList<C extends Character> list) { 
     characters = list; 
    } 
} 

public class HeroesGroup extends CharactersGroup<Hero> { 
    // Here is an ArrayList<Character> characters, that I would like to "become" an ArrayList<Hero> characters 

    public HeroesGroup() { 
     this(new ArrayList<Hero>()); 
    } 

    public HeroesGroup(ArrayList<Hero> list) { 
     super(list); 
    } 
} 
相關問題