如何使用定义类型的泛型类的方法?

时间:2013-06-09 17:46:46

标签: java generics

public class Team<AbstractMember> {

    public int getPoints() {
        int points = 0;
        for (AbstractMember member : memberList) {
            points += member.**getPoints()**;
        }
        return points;
    }
}

我想查看成员的要点并返回它们,但事实上,AbstractMember是泛型类的类型会禁用方法member.getPoints()。 Eclipse说The method getPoints() is undefined for the type AbstractMember

public abstract class AbstractMember{
    private String name;
    private int points;

    public int getPoints() {
        return points;
    }
}

如何使用已定义类型的泛型类的方法?

1 个答案:

答案 0 :(得分:6)

更改此声明

public class Team<AbstractMember>

public class Team<T extends AbstractMember>

然后,在您的代码中,您应该使用T来引用类Type。例如,您必须更改for循环来自

for (AbstractMember member : memberList)

for (T member : memberList) {