Field masks field in super class¶
ID: java/field-masks-super-fieldKind: problemSecurity severity: Severity: warningPrecision: mediumTags: - quality - maintainability - readability - correctnessQuery suites: - java-security-and-quality.qls
Click to see the query in the CodeQL repository
A field that has the same name as a field in a superclasshides the field in the superclass. Such hiding might be unintentional, especially if there are no references to the hidden field using thesuper qualifier. In any case, it makes code more difficult to read.
Recommendation¶
Ensure that any hiding is intentional. For clarity, it may be better to rename the field in the subclass.
Example¶
In the following example, the programmer unintentionally added anage field toEmployee, which hides theage field inPerson. The constructor inPerson sets theage field inPerson to 20 but theage field inEmployee is still 0. This means that the program outputs 0, which is probably not what was intended.
publicclassFieldMasksSuperField{staticclassPerson{protectedintage;publicPerson(intage){this.age=age;}}staticclassEmployeeextendsPerson{protectedintage;// This field hides 'Person.age'.protectedintnumberOfYearsEmployed;publicEmployee(intage,intnumberOfYearsEmployed){super(age);this.numberOfYearsEmployed=numberOfYearsEmployed;}}publicstaticvoidmain(String[]args){Employeee=newEmployee(20,2);System.out.println(e.age);}}
To fix this, delete the declaration ofage on line 11.
References¶
Help - Eclipse Platform:Java Compiler Errors/Warnings Preferences.
The Java Tutorials:Hiding Fields.