在子类中将属性ArrayList <class>更改为ArrayList <subclass>

时间:2017-01-12 23:28:56

标签: java arraylist

嗨,你好,这是我的问题。

我想知道,如果给定abstract class Foo,是否有可能以某种方式获得其属性ArrayList<Bar>(Bar也是抽象的)只包含它所使用的某个特定子类包含在Foo的每个子类中。

例如,在具有class FooChild的具体extends Foo中,属性ArrayList<Bar>现在只包含具体的class BarChildextends 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就像:

public abstract class Character {
    private String name;

    public Character(String n) {
        name = n;;
    }
}

Hero一样:

public class Hero extends Character {
    private int level;

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

2 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分:0)

您可以将抽象类function scrollHandler (event) { $(document).off("mousewheel.custom"); var delta = event.originalEvent.wheelDelta if(delta < 0){ $('html, body').animate({ scrollTop: $("#content-wrapper").offset().top }, 3000, function () { // animation callback function $(document).on("mousewheel.custom", scrollHandler); })); } else { $('html, body').animate({ scrollTop: $("#bgheader").offset().top }, 3000, function () { // animation callback function $(document).on("mousewheel.custom", scrollHandler); }); } } // namespace the event so we can easily .off() it $(document).on('mousewheel.custom', scrollHandler); 设为通用。

fos_user_change_password:
    resource: "@FOSUserBundle/Resources/config/routing/change_password.xml"
    prefix: /profile

子类看起来像这样:

sonata_user_change_password:
    resource: "@SonataUserBundle/Resources/config/routing/sonata_change_password_1.xml"
    prefix: /profile