栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java接口-它们的作用是什么?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java接口-它们的作用是什么?

接口允许您在运行时提供不同的实现,注入依赖项,单独的关注点,使用不同的实现进行测试。

只需将接口视为类保证实现的契约即可。实现该接口的具体类无关紧要。不知道这是否有帮助。

想出一些代码可能会有所帮助。这并不能解释界面的所有内容,请继续阅读,但我希望这可以帮助您入门。这里的重点是您可以更改实现…

package stack.overflow.example;public interface IExampleService {void callExpensiveService();}public class TestService implements IExampleService {@Overridepublic void callExpensiveService() {    // This is a mock service, we run this as many     // times as we like for free to test our software}}public class ExpensiveService implements IExampleService {@Overridepublic void callExpensiveService() {    // This performs some really expensive service,    // Ideally this will only happen in the field    // We'd rather test as much of our software for    // free if possible.}}public class Main {public static void main(String[] args) {    // In a test program I might write    IExampleService testService = new TestService();    testService.callExpensiveService();    // Alternatively, in a real program I might write    IExampleService testService = new ExpensiveService();    testService.callExpensiveService();    // The difference above, is that we can vary the concrete     // class which is instantiated. In reality we can use a     // service locator, or use dependency injection to determine     // at runtime which class to implement.    // So in the above example my testing can be done for free, but     // real world users would still be charged. Point is that the interface    // provides a contract that we know will always be fulfilled, regardless     // of the implementation.}}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/507326.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号