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

查看:170
本文介绍了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.

通常你需要一个接口:


  • 您的程序将为您的组件提供多种实现。例如,作为代码一部分的默认实现,以及在JUnit测试中使用的模拟实现。有些工具可以自动创建模拟实现,例如EasyMock。

  • 您希望对此类使用依赖注入,使用Spring或JBoss Micro-Container等框架。在这种情况下,最好使用接口从一个类和其他类指定依赖项。

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

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