I have a class called Flamethrower which naturally has its own ammunition that is distinct from other weapons. Should this ammunition be a nested class within flamethrower as only flamethrower will ever use this class?
-
4Personally, I'm not sure nested classes are ever a good idea. Anonymous classes for event handlers - sure. Multiple classes in the same module: yes. Nested classes: I'd use inheritance or composition before I'd use nesting. IMHO...paulsm4– paulsm42012-06-17 03:53:38 +00:00Commented Jun 17, 2012 at 3:53
-
1@paulsm4 - Actually the decision to use nested classes is independent from whether to use inheritance or composition etc.Paul Bellora– Paul Bellora2012-06-17 04:30:27 +00:00Commented Jun 17, 2012 at 4:30
2 Answers
I'm going to delete my comment and make this an answer:
Should this ammunition be a nested class within flamethrower
I don't think so, the reason being that the ammunition will interact with the target as well, and so its effects are felt beyond that of its host weapon. I usually reserve inner classes for "helper" classes that are used only inside of the outer class.
Comments
You probably shouldn't have a class at all. Generally, you want stuff like this to be scriptable, for ease of development and modding. You should replace it with a generic ammo class that reads values from a data file in order to customize behavior unless you have a really good reason not to. In general, a common mistake among Java beginners is to make classes for everything whether they need it or not.