2

I tried to understand the use of interface and read this article which says:

Interfaces define a standardized set of commands that a class will obey.

The commands are a set of methods that a class implements.

The interface definition states the names of the methods and their return types and argument signatures. There is no executable body for any method that is left to each class that implements the interface.

I would like to ask why do I need to state name of methods and their return types and argument signatures in an interface while I can implement them directly in a class?

4

1 回答 1

2

以最简单的方式,我会说主要用途是多态性,即对多个不同对象执行相同操作的能力。

这里:-

接口是类可以做什么的契约(或协议,或共同理解)。当一个类实现某个接口时,它承诺为接口中声明的所有抽象方法提供实现。接口定义了一组常见的行为。实现接口的类同意这些行为,并为这些行为提供自己的实现。这允许您在接口处编程,而不是在实际实现中进行编程。接口的主要用途之一是提供两个对象之间的通信契约。如果您知道一个类实现了一个接口,那么您就知道该类包含该接口中声明的方法的具体实现,并且您可以保证能够安全地调用这些方法。换句话说,

其次,Java 不支持多重继承(而 C++ 支持)。多重继承允许您从多个直接超类派生一个子类。如果两个直接超类有冲突的实现,这会带来问题。(在子类中要遵循哪一个?)。但是,多重继承确实有它的位置。Java 通过允许您“实现”多个接口来做到这一点(但您只能从单个超类“扩展”)。由于接口只包含没有实际实现的抽象方法,因此多个接口之间不会出现冲突。(接口可以保存常量,但不推荐。如果子类实现了两个常量冲突的接口,编译器会标记出编译错误。)

于 2013-09-02T21:30:32.257 回答