问题
I got the following objects:
public class DbRepository<T> implements DbRepositoryInterface<T>{
protected T model;
protected DbRepository(T model) {
System.out.println("DbRepository created.");
this.model = model;
}
@Override
public T getModel() {
return model;
}
}
public interface DbRepositoryInterface<T> {
public T getModel();
}
public class PlayerDbRepository extends DbRepository<Player> {
}
In my code, where I want to make use of the PlayerDbRepository I would like to call:
DbRepositoryInterface<Player> repo = new PlayerDbRepository();
But in the PlayerDbRepository I get a warning about my constructor in the parent class DbRepository. What do I have to modify to make this work? Or is my approach on this wrong?
回答1:
The DbRepository class has a required constructor that takes a T. Since your PlayerDbRepository subclasses this DbRepository, you must call the parent constructor with a T instance.
You can do this 2 ways:
making a similar constructor in the child class that takes a Player and delegates it to the parent constructor:
public class PlayerDbRepository extends DbRepository<Player> { public PlayerDbRepository(Player model){ super(model); } }Create a Player instance some other way and pass it in
public class PlayerDbRepository extends DbRepository<Player> { public PlayerDbRepository(){ super(new Player()); } }
Of course you can always combine both solutions so users of the code can choose which option is best for them.
public class PlayerDbRepository extends DbRepository<Player> {
/**
* Creates new Repository with default Player.
*/
public PlayerDbRepository(){
super(new Player());
}
/**
* Creates new Repository with given Player.
*/
public PlayerDbRepository(Player model){
super(model);
}
}
回答2:
DbRepositoryInterface is interface.
You cannot create an interface object.
One thing you can do is by implementing Factory class, to map your interface with your repository classes. Normally we use tools to do that.
Your instantiation would then be like below: DbRepositoryInterface repo = FactoryClass.GetInstanceOf(); which in turn, you will return PlayerDbRepository object anyway.
Thank you,
来源:https://stackoverflow.com/questions/26226955/dbrepository-implementation-without-constructor-in-child-classes