Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement a generic interface

Tags:

java

generics

I have a generic interface and I would like to implement this interface in a generic way :

public interface BaseBean<T> {

    public T create(T t);
    public T read(Long id);
    public T update(T t);
    public void delete(T t);

}

For some reason, I can't make the implementation generic as well. Eclipse implements all interface methods in non-generic way:

public class BaseBeanImpl<T> implements NewBaseBean {

    @Override
    public Object create(Object t) {
        return null;
    }

    @Override
    public Object read(Long id) {
        return null;
    }

    @Override
    public Object update(Object t) {
        return null;
    }

    @Override
    public void delete(Object t) {
    }

    @Override
    public Object find(Long id) {
        return null;
    }
}

When I change:

public Object create(Object t)

to

public T create(T t)

I get a compile error. Did I miss something?

like image 300
jarosik Avatar asked Jul 20 '15 12:07

jarosik


1 Answers

Change

public class BaseBeanImpl<T> implements NewBaseBean

to

public class BaseBeanImpl<T> implements NewBaseBean<T>

When you use the raw type NewBaseBean, you get Object instead of T in your interface's methods.

public class BaseBeanImpl<T> implements NewBaseBean<T> {

  @Override
  public T create(T t) {
      return null;
  }

  @Override
  public T read(Long id) {
      return null;
  }

  @Override
  public T update(T t) {
      return null;
  }

  @Override
  public void delete(T t) {
  }

  @Override
  public T find(Long id) {
      return null;
  }
}
like image 122
Eran Avatar answered Sep 19 '22 16:09

Eran