检查字段是否被覆盖

发布于 2025-01-01 12:30:26 字数 286 浏览 3 评论 0原文

checkstyle 是否具有检查子类是否覆盖父类的公共或受保护字段的规则。

例如,

class Ancestor {
   public static final int VALUE = 123;
}

class Descendant extends Ancestor {
   public static final int VALUE = 100; // <-- this is unwanted
}

我想以某种方式使用 checkstyle 来禁止这种情况。

Does checkstyle has rule which checks if subclass overrides public or protected field of a parent class.

For example

class Ancestor {
   public static final int VALUE = 123;
}

class Descendant extends Ancestor {
   public static final int VALUE = 100; // <-- this is unwanted
}

I want somehow with checkstyle to forbid such situation.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风吹过旳痕迹 2025-01-08 12:30:26

覆盖语义不适用于静态字段。当您访问 Descendant 中的 VALUE 时,将使用 100 作为值。您还可以使用 Ancestor.VALUE 引用超类的 VALUE。

现在,避免混淆的最佳方法是始终通过类名(如 Ancestor.VALUE 和 Descendant.VALUE)限定静态成员来访问静态成员。 IDE(如 Eclipse)允许您强制执行此规则,但在任何静态代码分析工具中都没有看到此规则。下面是如何在 Eclipse 中强制执行此操作的屏幕截图

在此处输入图像描述

Override semantics are not applicable for static fields. When you access VALUE in Descendant then 100 is used as the value. You can also reference superclass's VALUE using Ancestor.VALUE.

Now, the best way to avoid confusion is to always access static members by qualifying it with class name like Ancestor.VALUE and Descendant.VALUE. The IDE's (like eclipse) let you enforce this rule but didn't see this in any of static code analysis tools. Below is the screenshot on how to enforce this in eclipse

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文