如何覆盖超级构造函数

时间:2015-02-03 22:36:24

标签: java templates

我扩展了一个具有模板参数TService:

的超类
public abstract class SupplySideServer<TService extends SupplySideService, TRequest extends Request, TResponse extends Response> {

protected TService service;

public SupplySideServer(TService service) {
    this.service = service;
}

我有一个子类:

public class SupplySideServerImpl<TService extends SupplySideService, TRequest extends Request, TResponse extends Response> {

//public SupplySideServerImpl(Class<? extends SupplySideService<T>> service) {
    public SupplySideServerImpl(TService service) {
    super(service);
}

但它不会编译,如何将服务传递给子类?我是否必须在超类/抽象类中使用子类中的模板参数?

1 个答案:

答案 0 :(得分:0)

您的子类 SupplySideServerImpl 似乎没有扩展父类 SupplySideServer 。因此,编译器认为您的子类 SupplySideServerImpl 仅隐式扩展 Object 类(因为我们知道Java中的每个类都扩展了Object类)。由于 Object 类的默认构造函数是一个无参数构造函数,因此对超类构造函数的调用应该没有参数。我认为您的代码中的以下更改应该有效。如果我错了,请纠正我。

public class SupplySideServerImpl<TService extends SupplySideService, TRequest extends Request, TResponse extends Response> extends SupplySideServer<TService extends SupplySideService, TRequest extends Request, TResponse extends Response>{

        public SupplySideServerImpl(TService service) {
        super(service);
    }
}