Type bound extends a final class¶
ID: java/type-bound-extends-final
Kind: problem
Security severity:
Severity: warning
Precision: medium
Tags:
- maintainability
- readability
- types
Query suites:
- java-security-and-quality.qls
Click to see the query in the CodeQL repository
A type wildcard with an extends
clause (for example ? extends String
) implicitly suggests that a type (in this case String
) has subclasses. If the type in the extends
clause is final, the code is confusing because a final class cannot have any subclasses. The only type that satisfies ? extends String
is String
.
Recommendation¶
To make the code more readable, omit the wildcard to leave just the final type.
Example¶
In the following example, a wildcard is used to refer to any type that is a subclass of String
.
class Printer
{
void print(List<? extends String> strings) { // Unnecessary wildcard
for (String s : strings)
System.out.println(s);
}
}
However, because String
is declared final
, it does not have any subclasses. Therefore, it is clearer to replace ? extends String
with String
.
References¶
Help - Eclipse Platform: Java Compiler Errors/Warnings Preferences.
Java Language Specification: 4.5.1 Type Arguments of Parameterized Types , 8.1.1.2 final Classes.