Reputation: 931
I learned that inner classes are to be used when an object is closely associated with another object. So a LinkedList class might contain an inner Node class, since each Node exists only in its LinkedList.
I'm thinking about making a game, and am considering making a Map object, with a double array of Tiles, where each Tile is an inner class.
But then I thought that really, the Map class should be an inner class inside the Game class.
Thus we have
class Game {
class Map {
Tile[][] grid;
class Tile {
...
}
...
}
class Unit {
...
}
class Player {
...
}
...
}
However, this seems excessive, since it results in just one, massive file. Is this a problem? Or am I completely misunderstanding the point of inner classes?
What are the factors one should consider when choosing to make your new class inner or outer and, if the choice is inner, when should the inner class be static
?
Upvotes: 13
Views: 2268
Reputation: 41188
When to use inner classes is as much art as it is science. Basically look at how big your code file is getting and how big each class is. If a class is big and complicated it should probably go in its own file. If it's small (for example a single function implementation of a listener interface) and unlikely to be re-used elsewhere then it should probably be an inner class.
In fact re-use is probably one of the most important criteria. Anything that can be re-used should be re-used and should be scoped appropriately to enable that.
An important advantage of inner classes is that they can help with encapsulation, keeping the internal implementation of your class internal. If other classes do not need to know about your inner classes (or in some cases even that they exist) then that is an excellent reason for them to be inner.
Upvotes: 7
Reputation: 11017
The question I would ask is 'Does the inner class make sense as a concept unto itself?' Does an object of type Map
have meaning, or does Game.Map
add significant value?
I would Map
makes sense on its own, and should therefore be an outer class. You can then specify the close relationship of Game and Map using namespaces.
Upvotes: 1
Reputation: 525
In the game example that you are trying to implement, y. Map and tiles can be an appropriate data structure rather then separate inner classes. Any specific requirements of having them as classes?
Upvotes: 0
Reputation: 310957
It's not a question of 'too many', at least not until you hit some hard limit. It's a question of what can reasonably be said to belong inside what. A Map will always have Entries, which can be an inner class. A Game won't always have have a Map, so the Map shouldn't be inner to Game.
Upvotes: 1
Reputation: 2562
At my own opinion, inner class are just useless and lead to bad design, using access that should not be granted, making the code unclear. Just forgot about it.
(At my own opinion, of course)
Upvotes: -4