Static Field Accessed Through a Subclass Name
ID |
java.static_base_class_members_accessed |
Severity |
high |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Java |
Tags |
code-style, reliability |
Description
Reports a static field accessed through the name of a subclass, when the field is declared in one of that subclass’s superclasses.
Rationale
A static field belongs to the class that declares it, not to any subclass that happens to inherit it. Qualifying the access with a subclass name compiles fine — Java resolves it through inheritance — but it misleads a reader into thinking the field is owned by, or specific to, that subclass, and it silently keeps working even after the field moves further up the hierarchy.
class Counter {
static int total;
}
class RequestCounter extends Counter {
void increment() {
RequestCounter.total++; // Bad -- total belongs to Counter
}
}
Remediation
Qualify the access with the class that actually declares the field.
class Counter {
static int total;
}
class RequestCounter extends Counter {
void increment() {
Counter.total++; // Good -- access matches ownership
}
}