gpt4 book ai didi

java - 使用 Java 中的接口(interface)作为与更多团队一起处理代码的方法

转载 作者:行者123 更新时间:2023-12-01 07:45:09 25 4
gpt4 key购买 nike

我在准备 Java OCA 考试时遇到了这个问题和回答。

Imagine you are working with another team to build an application. You are developing code that uses a class that the other team has not finished writing yet. Which element of Java would best facilitate this development, allowing easy integration once the other team’s code is complete?

A. An abstract class

B. An interface

我已经回答了 A,但真正的答案是 B。

原因是:

The key here is understanding which of these features of Java allow one developer to build their application around another developer’s code, even if that code is not ready yet. For this problem, an interface is the best choice. If the two teams agree on a common interface, one developer can write code that uses the interface, while another developer writes code that implements the interface. Assuming neither team changes the interface, the code can be easily integrated once both teams are done. For these reasons, Option B is the correct answer.

我不明白如何在不实现接口(interface)的情况下使用它。

最佳答案

关键在于“一个开发人员可以编写使用该接口(interface)的代码”,即您可以编写适用于实现该接口(interface)的类的实例的代码,并调用它们的方法,而无需实际知道这些实例将是什么类,也不知道这些实例是什么。可能会破坏您的代码的实现细节。

因此,编写代码意味着您可以编译它,但除非提供实现,否则应用程序当然不会运行。一种实现可能是一个模型,它对于测试目的很有用,但使用抽象类很难做到。

为什么抽象类在许多情况下是一个较差的选择?原因之一是一个类只能有一个直接父类(super class),因此不能从多个独立的抽象类继承,而实现多个独立的接口(interface)很容易。除其他外,这可以让您减少耦合,因为您不必将不相关的方法放入单个类中。

关于java - 使用 Java 中的接口(interface)作为与更多团队一起处理代码的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54588405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com