← 返回首页
Inner class could be static — CodeQL query help documentation CodeQL docs
CodeQL documentation
CodeQL resources

Inner class could be static

ID: java/non-static-nested-class Kind: problem Security severity: Severity: recommendation Precision: high Tags: - quality - maintainability - readability Query suites: - java-code-quality.qls - java-security-and-quality.qls

Click to see the query in the CodeQL repository

Nested classes allow logical grouping of related concerns, increasing encapsulation and readability. However, there is a potential disadvantage when using them that you should be aware of.

Any non-static nested class implicitly holds onto its “enclosing instance”. This means that:

Recommendation

When a nested class does not need the enclosing instance, it is better to declare the nested class static, avoiding the implicit field. As a result, instances of the nested class become smaller, and hidden references to the enclosing class are made explicit.

If a reference to the enclosing class instance is required during construction of the nested class instance (but not subsequently), the constructor of the nested class should be refactored so that it is explicitly given a reference to the enclosing instance.

If the nested class refers to a type variable of an enclosing class instance, consider parameterizing the nested class by that type variable.

References