我目前正在处理另一个人项目的一些 Findbugs 问题。
这是我正在处理的问题:
Correctness - Class defines field that masks a superclass field
This class defines a field with the same name as a visible instance field in a superclass. This is confusing, and may indicate an error if methods update or access one of the fields when they wanted the other.
有父类(super class) OutputInterface
和扩展 OutputInterface
的子类 CoreOutputInterface
。它们都定义了变量className
。
CoreOutputInterface
也有一些子类。
要解决此问题,我只需从子类 (CoreOutputInterface
) 中删除 className
,因为它已在父类(super class)中定义。
永远不会使用 super.className
或 this.className
读取或设置变量,仅使用 className
,所以在我看来它不应该导致任何问题。
此外,整个项目中从未引用过父类(super class)中的变量(我使用 Eclipse 引用函数对其进行了检查)。
谁能确认这在任何情况下都不会导致问题?
预先感谢您的帮助。
输出接口(interface):
public abstract class OutputInterface {
protected String className = null;
...
}
核心输出接口(interface):
public abstract class CoreOutputInterface extends OutputInterface {
protected String className = null;
...
public void getClassName() {
return className;
}
public void setClassName(String newName) {
className = newName;
}
...
}
最佳答案
是的,从子类中删除声明。并像上面示例中那样提供/保留 getter,如果需要,还提供 setter。如果该字段从未使用过,它可能只是在创建“CoreOutputInterface”时被忽略了,因为开发人员可能复制粘贴了“OutputInterface”,然后对其进行了相应的编辑。
从理论上讲,根据类的复杂性和用途,这是或可能成为已知 SOLID OOP 设计原则的破坏Liskov 替换原则的示例.它指出父类(super class)对象必须始终可以用它们的子类对应物替换。鉴于所使用的两个“className”字段之间存在差异,一种方法可能会错误地依赖一个或另一个并导致未定义的行为,如报告中所述。
但是,我更困惑的是,为什么“类”被称为接口(interface)。
- 如果它真的是一个接口(interface),我们一开始就不会遇到这个问题,因为接口(interface)只允许常量。在那种情况下,getter 和 setter 就足够了。
- 如果它真的是一个类,那么应该从名称中去掉“接口(interface)”。否则,错误的名称只会妨碍理解,并可能在将来导致意想不到的副作用。
关于java - 子类和父类(super class)中的同名变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52327515/