luca89pe
luca89pe

Reputation: 107

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??

Upvotes: 0

Views: 163

Answers (3)

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

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.

Upvotes: 0

Bohemian
Bohemian

Reputation: 425033

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)

Upvotes: 0

omgBob
omgBob

Reputation: 527

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.

Upvotes: 2

Related Questions