简体   繁体   中英

Java Interface Inner Class

i'm still writing a Battleship game in java.
I'm having trouble to do it modular: I need to build the data classes (model) with an interface.
The idea i got is to build a class hierarchy like this:

BattleGrid => some methods, Grid => int rows, int cols, Cell[][] grid => char content

This means:
1. the public class is the BattleGrid class (which one that offers methods outside, like initGrid(), placeShip(), etc...);
2. then inside there is another class, the Grid, that contains the material grid and some info like grid rows and grid columns;
3. Inside every Cell, there is the content of that cell.
(obviously all with setters and/or getters)

The problems is: when i write this through a BattleGrid interface, inner classes are automatically declarated as public static.

Which is the proper way to do this kind of structure??

That's how interfaces work. Everything in a public interface is public. If you have member variables in it they are automatically static. Try using an abstract class instead or move the member variables to the implementing class.

Your question is quite broad, but I'll try yo answer it: it is best to keep things as simple as possible:

  • make your interfaces top level classes (ie in their own file)
  • don't use inner classes unless necessary (I doubt they would be for this)

In designing your interfaces, focus on the external functionality you want, and totally ignore how it is going to be implemented.

For example, if you have a need for a BattleGrid to be able to supply a Grid externally, you can declare them both as separate interfaces with Grid getGrid(); as a method in BattleGrid . When writing a BattleGrid implementation you may choose to implement that by having a Grid implementation as an inner class in BattleGrid , but that has nothing at all to do with the BattleGrid interface.

If you don't need a BattleGrid to supply a Grid externally, don't mention Grid in the BattleGrid interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM