Inner Class Should Be Static
ID |
java.inner_should_be_static |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Java |
Tags |
efficiency |
Description
Reports non-static inner classes that never reference the enclosing class instance. A non-static inner class implicitly holds a reference to its enclosing instance, preventing garbage collection and increasing memory overhead.
Rationale
Every non-static inner class instance carries a hidden reference to its enclosing outer class instance. If the inner class never uses this reference, the memory overhead is wasted and can cause memory leaks.
public class Outer {
// Bad -- does not use Outer.this
class Inner {
public int compute() { return 42; }
}
}
Remediation
Declare the inner class static when it does not reference the enclosing instance.
public class Outer {
static class Inner {
public int compute() { return 42; }
}
}