What's the difference between having a class that isn't public in a file with another class that is public, and having a static inner class inside a public class? Why would one use one and not the other?
For example, say I have a file like so:
and another file like so:
What are the different situations where I'd want to use one of these files over the other?
You should never use the former. If you have two different top-level classes, they should be in different files. This makes it much easier to find them when you're looking for source code.
The second case is useful if the two classes are very tightly coupled, or the one class is just logically an internal part of the other class.
For instance, a GUI class could have internal classes that are event handlers. In this case, the two classes are very tightly coupled and the event handler can benefit from accessing the fields of the enclosing class directly.
An example of where one class could logically be an internal part of its enclosing class, is a ChessPiece which has an internal class Color. This way, a ChessPiece.Color is different from a Rainbow.Color.
Hebert Coelho wrote:In the book also says that if the inner class is privated you could leave its attributes public. [=
Yes, but there is no reason to do this. Better get into the good habit and make everything private always.
I do not know in pratice how it would be, but in the book he shows it as a good reason. You would reduce the number of the methods of the inner class. Once the inner class is private, the only one with access is the public class of the file.
Again, I do not worked with a system with inner classes yet so I do not know the impact of this kind of approach.