java - 如何初始化扩展子类未使用的抽象类字段
问题描述
这是我的问题:
我有这个抽象类:
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 字段可用于ServiceA或ServiceB。但是,在为ServiceA或ServiceB创建构造函数时,编译器会抛出我需要插入super();的错误。但我不需要这个字段可供子类使用,因为我不在那里使用它。我能做些什么来实现这一点。
解决方案
您不需要它对子类可用,但您确实需要它对子类可用,因为它用于someMethod
. ServiceA
因此,即使如此,您也必须将其传递给ServiceB
构造函数。
如果不是这种情况——someMethod
例如,如果被覆盖——那么你所拥有的是一个糟糕的设计,可能MyService
不应该在其中实现someMethod
.
推荐阅读
- .net-core - 在未授权用户的自定义身份验证中显示 AuthenticateResult.Fail("Invalid Token Used for Authorisation" )
- php - 从带有反斜杠的 API 检索的字符串中提取 URL
- flutter - Flutter:我有一个持久的自定义覆盖,里面有一个导航器。如何根据导航页面显示/隐藏覆盖?
- reactjs - React-sketch 给出错误“Uncaught TypeError: Cannot convert undefined or null to object at Function.getPrototypeOf”?
- javascript - discord.js message.author.id 在 dms 中返回 undefined 但在服务器中工作
- java - 将 LocalDateTime 转换为具有 0 偏移量的日期
- reactjs - 如何在本机反应中显示分数?
- r - 将字符集落形成单位转换为 R 中的数字科学记数法
- postgresql - 如何在peewee python中批量插入?
- python - 重新加载后无法腌制枚举:不是同一个对象