Java 接口方法论:每个类都应该实现一个接口吗? [英] Java Interfaces Methodology: Should every class implement an interface?

查看:26
本文介绍了Java 接口方法论:每个类都应该实现一个接口吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在大学的一些课程中一直在用 Java 编程,但我有以下问题:

I've been programming in Java for a few courses in the University and I have the following question:

在方法论上是否接受每个类都应该实现一个接口?不这样做是否被认为是不好的做法?你能描述一下使用接口不是一个好主意的情况吗?

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?

就我个人而言,我喜欢将接口用于所有事物的概念,作为一种方法论和习惯,即使它没有明显的好处.Eclipse 自动创建了一个包含所有方法的类文件,因此无论如何都不会浪费任何时间.

Personally, I like the notion of using Interfaces for everything as a methodology and habit, even if it's not clearly beneficial. Eclipse automatically created a class file with all the methods, so it doesn't waste any time anyway.

推荐答案

如果您不打算使用它,则无需创建界面.

You don't need to create an interface if you are not going to use it.

通常在以下情况下您需要一个接口:

Typically you need an interface when:

  • 您的程序将为您的组件提供多种实现.例如,作为代码一部分的默认实现,以及在 JUnit 测试中使用的模拟实现.一些工具会自动创建模拟实现,例如 EasyMock.
  • 您想对此类使用依赖注入,使用 Spring 或 JBoss Micro-Container 等框架.在这种情况下,最好使用接口指定一个类与其他类的依赖关系.

这篇关于Java 接口方法论:每个类都应该实现一个接口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆