Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with an inner class not using an outer class in Java?

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.

like image 616
user128807 Avatar asked Jul 15 '09 17:07

user128807


2 Answers

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;
    }
  }
}
like image 186
VonC Avatar answered Oct 15 '22 07:10

VonC


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.

like image 37
Chris Vest Avatar answered Oct 15 '22 08:10

Chris Vest