Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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 it's not making any reference to the outer class, it might as well be a full-on, regular class. Since it isn't dependent on the outer class, it can stand on its own. I suspect that's the reason for the "error".

A non-static inner class has an implicit reference to an instance of its outer class. This hidden reference can delay (or even prevent) garbage collection on the outer class and create serialization issues. So you should only use non-static inner classes when you need them. It is easy to forget to declare the class static, so the code analysis warns you when it isn't needed.

The whole point of the inner class is that it has access to the outer class. If you're not actually using the outer class, just make it a regular, full-blown class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top