Peter Bauer
Peter Bauer

Reputation: 45

How can I use a method of the defined type of the generic class?

public class Team<AbstractMember> {

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

I want to go over the points of the members and return them, but the fact, that AbstractMember is the type of the generic class disables the method member.getPoints(). Eclipse says The method getPoints() is undefined for the type AbstractMember.

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

    public int getPoints() {
        return points;
    }
}

How can I use a method of the defined type of the generic class?

Upvotes: 0

Views: 72

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85799

Change this declaration

public class Team<AbstractMember>

to

public class Team<T extends AbstractMember>

Then, in your code you should use T to refer to the class Type. For example, you will have to change the for loop you from

for (AbstractMember member : memberList)

to

for (T member : memberList) {

Upvotes: 6

Related Questions