【问题标题】:How to override super constructor如何覆盖超级构造函数
【发布时间】:2015-02-03 22:36:23
【问题描述】:

我扩展了一个具有模板参数 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);
}

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

【问题讨论】:

  • 好像你在类声明中忘记了extends SupplySideServer
  • 你不能重写构造函数,你只能调用它
  • 公共类 SupplySideServerImpl extends SupplySideServer {
  • 这是错误: - SupplySideServer 是原始类型。对泛型 SupplySideServer 的引用应该被参数化
  • 对我来说似乎不是一个错误。

标签: java templates


【解决方案1】:

您的子类 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);
    }
}

【讨论】:

  • 它不允许: - 令牌“SupplySideServer”上的语法错误,{ 预期在此令牌之后 - 语法错误,插入“}”以完成块
  • 我没有用错字,上面的错误是一样的。
  • 您能否更新您的代码(整个可能会有所帮助),并包括您得到的整个错误行。
  • 我只在实现类中扩展了类型化的参数来编译它。
猜你喜欢
  • 2014-04-11
  • 2021-01-17
  • 1970-01-01
  • 2011-05-14
  • 1970-01-01
  • 2014-06-09
  • 2016-07-16
  • 1970-01-01
  • 2016-02-27
相关资源
最近更新 更多