首页 > 解决方案 > 如何初始化扩展子类未使用的抽象类字段

问题描述

这是我的问题:

我有这个抽象类:

public abstract class MyService {
    private MyCache myCache;

    protected MyService(MyCache myCache){
        this.myCache = myCache;
    }

    void someMethod(){
        // work with the myCache
    }
}

现在我有一个子类如下:

public class ServiceA extends MyService {
    
    ServiceA () {  // getting error in this line

    }

    // some fields and implementations.

}

如果我这样做,错误会发生:

public class ServiceA extends MyService {

    private MyCache myCache;
    
    ServiceA (MyCache myCache) {  // getting error in this line
        super(myCache);
    }

    // some fields and implementations.
}

我的要求是我不需要 MyCache 字段可用于ServiceAServiceB。但是,在为ServiceAServiceB创建构造函数时,编译器会抛出我需要插入super();的错误。但我不需要这个字段可供子类使用,因为我不在那里使用它。我能做些什么来实现这一点。

标签: javaabstract-class

解决方案


您不需要它对子类可用,但您确实需要它对子类可用,因为它用于someMethod. ServiceA因此,即使如此,您也必须将其传递给ServiceB构造函数。

如果不是这种情况——someMethod例如,如果被覆盖——那么你所拥有的是一个糟糕的设计,可能MyService 不应该在其中实现someMethod.


推荐阅读