42 }
43 }
44
45 class Node {46 // Integer data4748 public Integer data;49 public Node nextNode;5051 // Previously, Object data52 Node(Node nextNode, Integer data) {53 this.nextNode = nextNode;54 this.data = data;55 }56 }57
58}
This nested class is declared without a static
modifier, meaning all instances of the class will hold a reference to an instance of the enclosing class.
The Java analyzer has detected that there are no explicit references to the enclosing class here, meaning this nested class can be safely treated as static.
Consider adding a static
modifier to the nested class.
Non-static nested classes are generally known as "inner" classes.
class Outer {
class Inner {
// ...
}
// ...
}
There are a number of things one should be aware of when using inner classes:
* An instance of Inner
will contain a reference to an instance of Outer
.
* If the Inner
instance continues to exist after all other references to the Outer
instance are deleted, the Outer
instance will still exist because of the reference held by the still-alive Inner
class.
* The syntax for instantiating a nested class is relatively obscure, and may confuse future code maintainers.
* Referring to private fields of the enclosing class from the nested class requires Java to generate synthetic accessor methods for that sole purpose, bloating the class's bytecode.
Declare the nested class as static if possible.
class Outer {
static class Inner {
// ...
}
// ...
}
If the inner class refers to the outer class's instance fields, this issue will not be reported.