java Java中接口的重要性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16761117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:55:49  来源:igfitidea点击:

The importance of interfaces in Java

javainterface

提问by Want

Let's say we have two classes, Tigerand Aeroplane. One thing in common for these two types is the Speed. I know that it would be illogical to create a superclass ClassWithSpeedand then derive subclasses Aeroplaneand Tigerfrom it. Instead, it is better to create an interface that contains the method speed()and then implement it in Aeroplaneand Tiger. I get that. But, we can do the same thing without interfaces. We could define method speed()in Aeroplaneand method speed()in Tiger. The only (maybe very big) flaw it would be that we couldn't "reach" the objects of Tigerand Aeroplanethrough an interface reference.

假设我们有两个类, TigerAeroplane。这两种类型的共同点是速度。我知道,这将是不合逻辑创建一个超类ClassWithSpeed,然后派生子类Aeroplane,并Tiger从它。相反,最好创建一个包含该方法的接口,speed()然后在Aeroplane和 中实现它Tiger。我明白了。但是,我们可以在没有接口的情况下做同样的事情。我们可以定义方法speed()inAeroplane和方法speed()in Tiger。唯一的(可能非常大)的缺陷这将是我们不能“达到”的目标Tiger,并Aeroplane通过接口引用。

I am beginner in Java and OOP, and I would be very grateful if someone explained to me the role of interfaces. Cheers!

我是 Java 和 OOP 的初学者,如果有人向我解释接口的作用,我将不胜感激。干杯!

回答by maybeWeCouldStealAVan

It's:

它的:

public int howFast(Airplane airplane) {
    return airplane.speed();
}

public int howFast(Tiger tiger) {
    return tiger.speed();
}

public int howFast(Rocket rocket) {
    return rocket.speed();
}

public int howFast(ThingThatHasntBeenInventedYet thingx) {
    // wait... what? HOW IS THIS POSSIBLE?!
    return thingx.speed();
}

...

vs

对比

public int howFast(Mover mover) {
    return mover.speed();
}

Now, imagine having to go back and change all those howFastfunctions in the future.

现在,想象一下howFast将来必须返回并更改所有这些功能。

Interface or no, each class will have to implement or inherit the speed()method. An interface lets you use those disparate classes more easily, because they've each promised to behave in a certain way. You'll call speed(), and they'll return an int, so you don't have to write separate methods for every possible class.

接口与否,每个类都必须实现或继承该speed()方法。接口使您可以更轻松地使用这些不同的类,因为它们都承诺以某种方式运行。您将调用speed(),他们将返回一个int,因此您不必为每个可能的类编写单独的方法。

When you find you need to handle speed differently because of a breakthrough in relativistic physics, you only need to update the methods that call speed(). When your great-granddaughter writes a class for HyperIntelligentMonkeyFish, she doesn't have to disassemble your ancient binary and make changes so that your code can monitor and control her mutant army. She needs only declare that HyperIntelligentMonkeyFish implements Mover.

当您发现由于相对论物理学的突破而需要以不同方式处理速度时,您只需更新调用speed(). 当您的曾孙女为 编写一个类时HyperIntelligentMonkeyFish,她不必分解您的古老二进制文件并进行更改,以便您的代码可以监视和控制她的变种人军队。她只需要声明HyperIntelligentMonkeyFish implements Mover

回答by Yishai

Interfaces allow Java, since it is statically typed, to work around multiple inheritance limitations to the degree felt worthwhile by the language designers.

接口允许 Java,因为它是静态类型的,可以在语言设计者认为值得的程度上解决多重继承限制。

In a dynamic language (like Python, Ruby, etc.) you can just call the speed method on any arbitrary object and discover at runtime if it is there or not.

在动态语言(如 Python、Ruby 等)中,您可以在任意对象上调用 speed 方法,并在运行时发现它是否存在。

Java, on the other hand, is statically typed, which means the compiler has to agree that the method will be there ahead of time. The only way to do that on classes that don't share common ancestry, and may only have Object in common, is an interface.

另一方面,Java 是静态类型的,这意味着编译器必须同意该方法将提前存在。在不共享共同祖先并且可能只有公共对象的类上执行此操作的唯一方法是接口。

Since objects can implement an arbitrary number of interfaces, this means you get the goodness of multiple inheritance (a single object that can pose as multiple different objects for different methods) without the downside (of conflicting implementations in the two super classes).

由于对象可以实现任意数量的接口,这意味着您可以获得多重继承的优点(单个对象可以为不同的方法构成多个不同的对象)而没有缺点(两个超类中的实现冲突)。

With Java 8, the designers of the language concluded that interfaces without any implementation was overly restrictive (they didn't like my solutionI guess ;-)), so they allow for a default implementation, thus expanding the multi-inheritance options of interfaces, while still trying to avoid the conflicting implementation problem via a complex set of precedence rulesso that there is an unambiguous default implementation to execute.

对于 Java 8,该语言的设计者得出结论,没有任何实现的接口过于严格(我猜他们不喜欢我的解决方案;-)),因此他们允许默认实现,从而扩展了接口的多继承选项,同时仍然试图通过一组复杂的优先规则来避免冲突的实现问题,以便有一个明确的默认实现来执行。

回答by stinepike

I am trying to explain the advantage of interface with the following example-

我试图用下面的例子来解释接口的优势——

suppose you have another class where you need to use the tiger or AeroPlane as parameter. So by using interface you can call using

假设您有另一个类,您需要使用老虎或飞机作为参数。因此,通过使用接口,您可以调用使用

someObject.someMethod(ClassWithSpeed)

but if you dont use interface you can use

但如果你不使用界面,你可以使用

someObject.someMethod(Tiger)
someObject.someMethod(AeroPlane)

Now what should you do? Your probable answer will be like, "I will use two overloaded method".

现在你应该怎么做?你可能的答案是这样的,"I will use two overloaded method".

This is okay so far, But

到目前为止还好,但是

Say you need to add more options (say car, cycle, rabbit, tortoise.... 100 others). So what will you do to make the change of your existing code?? you will need to change a lots of things..

假设您需要添加更多选项(比如汽车、自行车、兔子、乌龟……其他 100 种)。那么你会怎么做来改变你现有的代码?你需要改变很多东西..

The overall example above has only one purpose. That is to say

上面的整个示例只有一个目的。也就是说

"we need interface to create a better, reusable and properly object oriented design"

“我们需要接口来创建更好的、可重用的和正确的面向对象设计”

N.B.

NB

  1. if you are sure the program is too small and you will never need to change them then I think it is okay to implement without interface
  1. 如果您确定程序太小并且永远不需要更改它们,那么我认为没有接口也可以实现

回答by Andy Thomas

Defining an interface allows you to define methods that work not only on Aeroplane and Tiger, but also other classes that share the same interface.

定义接口允许您定义不仅适用于 Airplane 和 Tiger 的方法,还适用于共享相同接口的其他类。

For example, say your interface is IObjectWithSpeed. Then you can define a method like this -- in a single class that operates on IObjectWithSpeed objects.

例如,假设您的接口是 IObjectWithSpeed。然后您可以定义这样的方法——在对 IObjectWithSpeed 对象进行操作的单个类中。

  public double calculateSecondsToTravel( IObjectWithSpeed obj, double distance ) {
       return distance / obj.getSpeed();
  }

Interfaces allow us to satisfy the open/closed principle- open for extension, but closed for modification. The single implementation of the method above doesn't need to be modified as new classes are defined that implement IObjectWithSpeed.

接口允许我们满足开放/封闭原则——对扩展开放,对修改封闭。上述方法的单一实现不需要修改,因为定义了实现 IObjectWithSpeed 的新类。

回答by anana

Aside from being descriptive for those classes' functionality, methods of an interface could be used without any knowledge about the classes implementing it, even for classes that were not yet defined.

除了描述这些类的功能之外,接口的方法可以在不了解实现它的类的情况下使用,即使是尚未定义的类。

So for example, if you'd need a class Transportthat computes say efficient routes, it could be given a class that implements ClassWithSpeedas a parameter and use its method speed()for computing what it needs. This way you could use it with our class Aeroplane, but also with any class we define later, say Boat. Java will take care that if you want to use a class as a parameter to Transportit will implement ClassWithSpeed, and that any class implementing ClassWithSpeedimplements the method speed()so that it can be used.

因此,例如,如果您需要一个Transport计算高效路由的类,可以给它一个实现ClassWithSpeed为参数的类,并使用其方法speed()计算所需的内容。这样你就可以在我们的类中使用它Aeroplane,也可以在我们稍后定义的任何类中使用它,比如Boat。Java 会注意,如果你想使用一个类作为Transport它的参数,它将会实现ClassWithSpeed,并且任何ClassWithSpeed实现的类都实现了该方法,speed()以便它可以被使用。

回答by Ankur Trapasiya

I want go into much theoretical details but will try to explain using this example.

我想深入研究很多理论细节,但会尝试使用这个例子来解释。

Consider JDBC API. It is API used to deal with database related options in the Java. Now, there are so many databases in the industry. How would one write drivers for that? Well, the quick and dirty approach may be write own implementation using our own classes and API.

考虑JDBC API。它是Java 中用于处理数据库相关选项的API。现在,业界有这么多的数据库。如何为此编写驱动程序?好吧,快速而肮脏的方法可能是使用我们自己的类和 API 编写自己的实现。

But think from the programmer's perspective. Will they start learning DATABASE DRIVER's API while using different database? The answer is NO.

但是从程序员的角度考虑。他们会在使用不同的数据库时开始学习DATABASE DRIVER的 API 吗?答案是不。

So what is the solution to the problem ? Just have a well defined API which anyone can extend for his own implementation.

那么问题的解决方法是什么?只要有一个定义良好的 API,任何人都可以为他自己的实现扩展它。

In JDBC API, there are some Interfaces which are Connection, ResultSet, PreparedStatement, Statement etc. Now each database vendor will implement the interface and will write his own implementation for that. Result ? : Reduced effort from the developer and easy understandability.

在JDBC API 中,有一些接口,它们是Connection、ResultSet、PreparedStatement、Statement 等。现在每个数据库供应商都会实现该接口并为此编写自己的实现。结果 ?:减少了开发人员的工作量并且易于理解。

Now, what this custom implementation might consisting of ? It's simple. They do what, take ResultSet interface for example and implement it and in whatever method the ResultSet is gettting returned, return THE CLASS THAT IMPLEMENTSResultSet interface like this

现在,这个自定义实现可能包含什么?这很简单。他们做什么,采取ResultSet接口,例如和实施,并在任何方法流汗返回的ResultSet,返回类实现ResultSet接口这样的

ResultSet rs=new ResultSetImpl(); //this is what they are doing internally.

结果集 rs=new ResultSetImpl(); //这是他们在内部做的事情。

So interface are like contracts. They define what your class is able to do and they give your application flexibility. You can create your own APIs using interfaces properly.

所以接口就像合同。它们定义了您的类能够做什么,并赋予您的应用程序灵活性。您可以正确使用接口创建自己的 API。

Hope this helps you.

希望这对你有帮助。

回答by scottb

An interface is not simply a method signature.

接口不仅仅是一个方法签名。

It is a type that represents a contract. The contract is the thing, not the method signatures. When a class implements an interface, it is because there is a contract for a shared behavior that the class has an interest in implementing as a type. That contract is implemented via the specified members which are usually method bodies but may also include static final fields.

它是一种表示合约的类型。契约是事物,而不是方法签名。当一个类实现一个接口时,是因为有一个共享行为的契约,这个类有兴趣实现为一个类型。该合约是通过指定的成员实现的,这些成员通常是方法主体,但也可能包含静态最终字段。

It may be true that a tiger and an aeroplane both could be expressed as a type with a common behavior implemented through speed() ... and if so, then the interface represents the contract for expressing that behavior.

老虎和飞机都可以表示为具有通过 speed() 实现的共同行为的类型,这可能是真的……如果是这样,则接口表示表达该行为的契约。

回答by Ryan Ransford

The interface (as a language construct) is used by the compiler to prove that the method call is valid and allows you to have dependent classes interact with the implementing class while having the least possible knowledge about the implementing class.

编译器使用接口(作为语言构造)来证明方法调用是有效的,并允许您让依赖类与实现类交互,同时对实现类有最少的了解。

回答by Mikhail

This is a very wide question to give a simple answer. I can recommend a book Interface Oriented Design: With Patterns. It explains all power of interfaces. And why we should not avoid them.

这是一个非常广泛的问题,可以给出一个简单的答案。我可以推荐一本书Interface Oriented Design: With Patterns。它解释了接口的所有功能。以及为什么我们不应该避免它们。

回答by Bobby Marinoff

On language level, the only use of interfaces is, like you mentioned, to be able to refer to different classes in a common way. On people level, however, the picture looks different: IMO Java is strong when used in big projects where the design and the implementation are done by separate people, often from separate companies. Now, instead of writing a specification on a Word document, the system architects can create a bunch of classes that implementers can then directly insert in their IDEs and start working on them. In other words it is more convenient instead of declaring that "Class X implements methods Y and Z in order for it to be used for purpose A, just to say that "Class X implements interface A"

在语言级别,接口的唯一用途是,就像您提到的那样,能够以通用方式引用不同的类。然而,在人员层面,情况看起来有所不同:IMO Java 在设计和实施由不同的人(通常来自不同的公司)完成的大型项目中使用时非常强大。现在,系统架构师可以创建一堆类,而不是在 Word 文档上编写规范,然后实现者可以直接将这些类插入到他们的 IDE 中并开始处理它们。换句话说,它比声明“X 类实现方法 Y 和 Z 以便将其用于目的 A”更方便,只是说“X 类实现接口 A”