我在大学的几门类(class)中使用 Java 编程,我有以下问题:
Is it methodologically accepted that every class should implement an interface? Is it considered bad practice not to do so? Can you describe a situation where it's not a good idea to use interfaces?
编辑:就我个人而言,我喜欢将接口(interface)作为一种方法论和习惯使用的概念,即使它不是明显有益的。 Eclipse 自动创建了一个包含所有方法的类文件,因此无论如何也不会浪费任何时间。
最佳答案
如果你不打算使用它,你不需要创建一个接口(interface)。
通常在以下情况下您需要一个接口(interface):
- 您的程序将为您的组件提供多种实现。例如,作为代码一部分的默认实现,以及在 JUnit 测试中使用的模拟实现。一些工具会自动创建模拟实现,例如 EasyMock。
- 您希望使用 Spring 或 JBoss Micro-Container 等框架对此类使用依赖注入(inject)。在这种情况下,最好使用接口(interface)指定一个类与其他类的依赖关系。
关于Java 接口(interface)方法论 : Should every class implement an interface?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2659366/