我什么时候应该在java中使用接口? [英] When should I use an interface in java?

查看:279
本文介绍了我什么时候应该在java中使用接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中专门使用接口的一个很好的例子是理想的,并且适用于任何特定的规则。

A good example of when exactly to use interfaces specifically in Java would be ideal and any specific rulings that apply.

推荐答案

使用接口来定义应用程序编程合同(蓝图,接口),第三方供应商必须完全遵守和实施。通过这种方式,最终用户可以根据API合同进行编码,并在不更改代码的情况下轻松切换具体实现。

Use interfaces to define an application programming contract (blueprint, interface) which "3rd-party" vendors have to fully adhere and implement. This way the endusers can just code against the API contract and easily switch of the concrete implementation "under the hoods" without changing the code.

JDBC API 就是一个很好的例子。它几乎只存在接口。具体实现提供为JDBC驱动程序。这使您可以独立于数据库(DB)供应商编写所有JDBC代码。只要您想切换数据库供应商,就可以更改JDBC驱动程序而无需更改任何Java代码行(任何硬编码的特定于DB的SQL代码除外)。

The JDBC API is an excellent example. It exist of almost only interfaces. The concrete implementations are provided as "JDBC drivers". This enables you to write all the JDBC code independent of the database (DB) vendor. You can just change the JDBC driver without changing any line of Java code (except of any hardcoded DB-specific SQL code) whenever you'd like to switch of DB vendor.

另一个例子是 Java EE API ,它还包含相当多的接口和抽象类。具体实现提供为Java EE应用程序服务器,Servletcontainers等,例如Sun Glassfish,Apache Tomcat等。这使您可以将Web应用程序(WAR)部署到您喜欢的任何Java Web服务器。

Another example is the Java EE API, it also contains pretty much interfaces and abstract classes. The concrete implementations are provided as "Java EE application servers", "Servletcontainers", etc, such as Sun Glassfish, Apache Tomcat, etc. This enables you to deploy the webapplication (WAR) to whatever Java web server you like.

这篇关于我什么时候应该在java中使用接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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