2014-10-07 71 views
0

我得到了以下对象:没有构造DbRepository实现在子类

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> { 
} 

在我的代码,在这里我想利用PlayerDbRepository的,我想打电话:

DbRepositoryInterface<Player> repo = new PlayerDbRepository(); 

但在PlayerDbRepository中,我收到了有关我的父类DbRepository中的构造函数的警告。我需要修改什么来完成这项工作?或者我的方法在这个错误?

回答

-1

DbRepositoryInterface是接口。

您无法创建接口对象。

你可以做的一件事是通过实现Factory类来映射你的接口和存储库类。通常我们使用工具来做到这一点。

您的实例化将如下所示: DbRepositoryInterface repo = FactoryClass.GetInstanceOf(); 反过来,你将返回PlayerDbRepository对象。

谢谢

+0

您可以通过创建实现接口的类或匿名类来创建接口对象。向工厂添加像工厂这样的额外图层不会导致OP的问题消失,只会将其推向另一层。 – dkatzel 2014-10-07 15:59:51

+0

你是对的。然后,尝试在父类上添加另一个空参数构造函数。 公共DbRepository(){} 应该做的伎俩。 – Jedi 2014-10-08 10:00:11

0

DbRepository类都需要有一个构造函数一个T。由于PlayerDbRepository的子类为DbRepository,因此必须使用T实例调用父构造函数。

你可以这样做2种方式:

  1. 使得在子类中类似的构造,需要一个播放器,并将其委托给父类的构造:

    public class PlayerDbRepository extends DbRepository<Player> { 
    
        public PlayerDbRepository(Player model){ 
         super(model); 
        } 
    } 
    
  2. 创建Player实例一些其他方式并通过它

    public class PlayerDbRepository extends DbRepository<Player> { 
    
        public PlayerDbRepository(){ 
         super(new Player()); 
        } 
    } 
    

当然,您始终可以结合使用这两种解决方案,以便代码的用户可以选择最适合他们的选项。

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); 
     } 
    } 
相关问题