CodeQL 文档

字段掩码超类中的字段

ID: java/field-masks-super-field
Kind: problem
Security severity: 
Severity: warning
Precision: medium
Tags:
   - maintainability
   - readability
Query suites:
   - java-security-and-quality.qls

单击以在 CodeQL 存储库中查看查询

与超类中的字段同名的字段隐藏超类中的字段。这种隐藏可能是无意的,特别是如果使用 super 限定符没有引用隐藏字段。无论如何,它都会使代码更难阅读。

建议

确保任何隐藏都是有意的。为了清楚起见,最好重命名子类中的字段。

示例

在以下示例中,程序员无意中向 Employee 添加了一个 age 字段,该字段隐藏了 Person 中的 age 字段。 Person 中的构造函数将 Person 中的 age 字段设置为 20,但 Employee 中的 age 字段仍然为 0。这意味着程序输出 0,这可能不是预期结果。

public class FieldMasksSuperField {
    static class Person {
        protected int age;
        public Person(int age)
        {
            this.age = age;
        }
    }

    static class Employee extends Person {
        protected int age;  // This field hides 'Person.age'.
        protected int numberOfYearsEmployed;
        public Employee(int age, int numberOfYearsEmployed)
        {
            super(age);
            this.numberOfYearsEmployed = numberOfYearsEmployed;
        }
    }

    public static void main(String[] args) {
        Employee e = new Employee(20, 2);
        System.out.println(e.age);
    }
}

要解决此问题,请删除第 11 行上 age 的声明。

参考

  • ©GitHub, Inc.
  • 条款
  • 隐私