在子类中没有构造函数的DbRepository实现 [英] DbRepository implementation without constructor in child classes

查看:614
本文介绍了在子类中没有构造函数的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 我想打电话:

In my code, where I want to make use of the PlayerDbRepository I would like to call:

DbRepositoryInterface<Player> repo = new PlayerDbRepository();

但是在 PlayerDbRepository 中我收到警告关于我的父类 DbRepository 中的构造函数。我需要修改才能使其工作?或者是我的这个错误的方法?

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?

推荐答案

DbRepository 一个需要一个 T 的构造函数。由于您的 PlayerDbRepository 将此 DbRepository 子类化,您必须使用 T 实例

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.

你可以这样做2种方法:

You can do this 2 ways:


  1. 在子类中创建一个类似的构造函数,该类可以使用Player并将其委托给父构造函数:

  1. 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);
   }
}


  • 创建一个Player实例,传递给

  • 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);
           }
        }
    

    这篇关于在子类中没有构造函数的DbRepository实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆