I'm using a static analyzer in Eclipse to examine my code. One class, foo, has an inner class, bar. I am getting the following error:
JAVA0043 Inner class 'bar' does not use outer class 'foo'
Why is this an error? As long as the outer class uses the inner class isn't that sufficient to make this information hiding useful and correct?
The inner class is not static.
Looks like an Enerjy Error:
// Incorrect
class Log {
// Position never uses the enclosing Log instance,
// so it should be static
class Position {
private int line;
private int column;
Position(int line, int column) {
this.line = line;
this.column = column;
}
}
}
A nested class that does not use any instance variables or methods from any of its outer classes can be declared static.
This reduces the dependency between the two classes, which enhances readability and maintenance.
// Correct
class Log {
static class Position {
private int line;
private int column;
Position(int line, int column) {
this.line = line;
this.column = column;
}
}
}
If the inner class can only ever be used by the outer class, yet the inner class needs no reference to the outer class, then you can make it private static
.
If the inner class is known to someone other than the outer class, then it might as well be a top-level class in its own right.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With