ant2009 ant2009 - 1 year ago 129
Java Question

Using generic interfaces and classes

java version "1.8.0_92"

I am trying to make a generic interface and a class that implements it. This is the interface:

interface UpdateDBListener<T> {
void onUpdateSuccess(T person);
void onUpdateFailure(String errMessage);
void updatePerson(T person, UpdateDBListener updateDBListener);


error: cannot find symbol method getId() where T is a type-variable: T extends Object declared in class PeopleListModelImp

And this is the class that implements it:

public class PeopleListModelImp<T> implements PeopleListModelContract<T> {

public void updatePerson(T person, UpdateDBListener updateListener) {
String id = person.getId(); /* ERROR */

The class I am using to pass in in this:

public class Person {
String mId;
String mFirstName;
String mLastName;

public Person() {

public String getId() {
return mId;

public void setId(String id) {
this.mId = id;

public String getFirstName() {
return mFirstName;

public void setFirstName(String firstName) {
this.mFirstName = firstName;

public String getLastName() {
return mLastName;

public void setLastName(String lastName) {
this.mLastName = lastName;

However, if I try to get the Id in the class that implements the interface I get an error on this line:

String id = person.getId();

I think as person don't know its a Person class, so doesn't understand the getId(). I am just wondering I am doing this an incorrect way. I want the class to be completely generic so I can using it for other different classes.

Is this possible?

Many thanks in advance.

Answer Source

It looks like you want to change

public class PeopleListModelImp<T> implements PeopleListModelContract<T> {


public class PeopleListModelImp<T extends Person> implements PeopleListModelContract<T> {

So that T knows that it's either a Person or a sub-class of Person.

Also, shouldn't

public void updatePerson(final T person, final UpdateDBListener updateListener) {

be changed to

public void updatePerson(final T person, final UpdateDBListener<T> updateListener) {

so that the method doesn't lose its genericity?

Note that in the future, you'll want to condense your code into a valid MCVE so that it's easier for the volunteers here to answer. Your posted code for instance did not include the PeopleListModelContract.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download