简体   繁体   English

Java接口内部类

[英]Java Interface Inner Class

i'm still writing a Battleship game in java. 我还在用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 BattleGrid =>一些方法,Grid => int rows,int cols,Cell [] [] grid => char内容

This means: 这意味着:
1. the public class is the BattleGrid class (which one that offers methods outside, like initGrid(), placeShip(), etc...); 1.公共类是BattleGrid类(提供外部方法的类,如initGrid(),placeShip()等...);
2. then inside there is another class, the Grid, that contains the material grid and some info like grid rows and grid columns; 2.然后在里面有另一个类Grid,它包含材质网格和一些信息,如网格行和网格列;
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. 问题是:当我通过BattleGrid接口写这个时,内部类会自动声明为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(); 例如,如果您需要BattleGrid能够在外部提供Grid ,则可以将它们声明为与Grid getGrid();单独接口Grid getGrid(); as a method in BattleGrid . 作为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. 在编写BattleGrid实现时,您可以选择通过将Grid实现作为BattleGrid的内部类来BattleGrid ,但这与BattleGrid接口没有任何关系。

If you don't need a BattleGrid to supply a Grid externally, don't mention Grid in the BattleGrid interface. 如果您不需要BattleGrid从外部提供Grid ,请不要在BattleGrid界面中提到Grid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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