This question already has answers here:
how to inherit Constructor from super class to sub class

(6个答案)


4年前关闭。




我创建了带有三个构造函数的抽象基类BaseModelDao。当我创建扩展SubscriberScoreDao的类BaseModelDao时,我必须在子类中重新定义所有三个构造函数,以避免编译时错误。有没有一种方法可以利用我在BaseModelDao中定义的构造函数,而不必在每个子类中重新实现相同的逻辑?

BaseModelDao

public abstract class BaseModelDao<T extends Model> {

    private static final String TAG = BaseModelDao.class.getSimpleName();

    private List<T> mModelList;

    protected BaseModelDao() {
        mModelList = new ArrayList<>();
    }

    protected BaseModelDao(Response<T>[] responseArray) {
        mModelList = fromResponseArray(responseArray);
    }

    protected BaseModelDao(Response<T> response) {
        mModelList = fromResponse(response);
    }

    public List<T> getModelList() {
        return mModelList;
    }

    public abstract Class<T> getModelClass();

    private List<T> fromResponse(Response<T> response) {
        List<T> responseList = response.getResultData();
        return responseList;
    }

    public List<T> fromResponseArray(Response<T>[] responseArray) {
        return fromResponse(getResponseObjectFromArray(responseArray));
    }

    // more helper methods...

}


SubscriberScoreDao

public class SubscriberScoreDao extends BaseModelDao<SubscriberScore> {

    public static final String TAG = SubscriberScoreDao.class.getSimpleName();

    public SubscriberScoreDao(){
        super();
    }

    public SubscriberScoreDao(Response<SubscriberScore>[] responseArray) {
        super(responseArray);
    }

    public SubscriberScoreDao(Response<SubscriberScore> responseArray) {
        super(responseArray);
    }

    @Override
    public Class<SubscriberScore> getModelClass() {
        return SubscriberScore.class;
    }
}


上面显示的构造函数是我要消除的构造函数。当我想在代码中使用SubscriberScoreDao时,它看起来像这样。

    LendingRestClient.getInstance().getSubscriberScoring(new Callback<Response<SubscriberScore>[]>() {
        @Override
        public void success(Response<SubscriberScore>[] responseArray, retrofit.client.Response response) {
            mSubscriberScoreDao = new SubscriberScoreDao(responseArray);
        }

        @Override
        public void failure(RetrofitError error) {

        }
    });


如果在super()中未定义调用SubscriberScoreDao的三个构造函数,则代码将在此行引发编译时错误:


mSubscriberScoreDao =新的SubscriberScoreDao(responseArray);


错误:


有没有一种方法可以不在每个子类中定义构造函数并避免此错误?

最佳答案

您可以使用vararg声明构造函数(在基类中):

class Super<T> {
    private List<T> responses;

    public Super(Response<T>...responses) {
        this.responses = Arrays.asList(responses);
    }
}


您的子类只需要声明1个构造函数,即可处理您拥有的所有3个构造函数的功能。

class Sub extends Super<SubscriberScore> {
    public Sub(Response<SubscriberScore>...responses) {
        super(responses);
    }
}


您现在可以将Sub实例化为:

new Sub();
new Sub(new Response<SubscriberScore>());
new Sub(new Response<SubscriberScore>[] {

});

10-08 19:26