java - 当我可以实现完整的类时,为什么还需要接口(interface)?

标签 java class oop

我试图理解 interface 的用法并阅读this article其中说:

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.

我想问为什么我需要在 interface 中声明方法名称及其返回类型和参数签名虽然我可以直接在 class 中实现它们?

最佳答案

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

来自here :-

An interface is a contract (or a protocol, or a common understanding) of what the classes can do. When a class implements a certain interface, it promises to provide implementation to all the abstract methods declared in the interface. Interface defines a set of common behaviors. The classes implement the interface agree to these behaviors and provide their own implementation to the behaviors. This allows you to program at the interface, instead of the actual implementation. One of the main usage of interface is provide a communication contract between two objects. If you know a class implements an interface, then you know that class contains concrete implementations of the methods declared in that interface, and you are guaranteed to be able to invoke these methods safely. In other words, two objects can communicate based on the contract defined in the interface, instead of their specific implementation.

Secondly, Java does not support multiple inheritance (whereas C++ does). Multiple inheritance permits you to derive a subclass from more than one direct superclass. This poses a problem if two direct superclasses have conflicting implementations. (Which one to follow in the subclass?). However, multiple inheritance does have its place. Java does this by permitting you to "implements" more than one interfaces (but you can only "extends" from a single superclass). Since interfaces contain only abstract methods without actual implementation, no conflict can arise among the multiple interfaces. (Interface can hold constants but is not recommended. If a subclass implements two interfaces with conflicting constants, the compiler will flag out a compilation error.)

关于java - 当我可以实现完整的类时,为什么还需要接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18580985/

相关文章:

c# - 在类中创建不需要由该类的对象调用的方法

java - 查找我定义的类的列表中是否存在具有给定变量值的元素

java - 从相机坐标计算世界坐标

c++ - C++如何防止导入循环

java - 如果子类在重写方法中强化了先决条件,那么在程序中会发生什么情况?

ruby - IRB 和 Ruby 对象模型

java - 单个字符串可以包含多行吗?

java - 在Java中以一定的时间间隔添加大量数据

javascript - 扩展 Web API 类构造函数