Java接口中的可选方法 [英] Optional Methods in Java Interface

查看:111
本文介绍了Java接口中的可选方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的理解,如果在java中实现接口,则该接口中指定的方法必须由实现所述接口的子类使用。

From my understanding if you implement an interface in java, the methods specified in that interface have to be used by the sub classes implementing the said interface.

I'我注意到在某些接口(如Collection接口)中有一些方法被注释为可选,但这究竟是什么意思?它让我有点兴奋,因为我认为界面中指定的所有方法都是必需的?

I've noticed that in some interfaces such as the Collection interface there are methods which are commented as optional, but what exactly does this mean? Its thrown me a bit as I thought all methods specified in the interface would be required?

推荐答案

似乎有很多糟糕的事情这里答案中的混淆。

There seems to be an awful lot of confusion in the answers here.

Java语言要求接口中的每个方法都是由该接口的每个实现实现的。期。 此规则没有例外。要说收藏集是一个例外,表明对此处的实际情况非常模糊。

The Java language requires that every method in an interface is implemented by every implementation of that interface. Period. There are no exceptions to this rule. To say "Collections are an exception" suggests a very fuzzy understanding of what's really going on here.

重要的是要意识到有两个级别符合接口:

It's important to realize that there are sort of two levels of conforming to an interface:


  1. Java语言可以检查的内容。这几乎归结为:每个方法都有一些实现吗?

实际履行合同。也就是说,实现是否按照界面中的文档说它应该做什么?

Actually fulfilling the contract. That is, does the implementation do what the documentation in the interface says it should?

编写良好的接口将包含准确解释实现期望的文档。您的编译器无法为您检查此内容。您需要阅读文档,并按照他们的意思行事。如果你没有按照合同所说的那样做,那么就编译器而言,你将有一个接口的实现,但它将是一个有缺陷/无效的实现。

Well written interfaces will include documentation explaining exactly what is expected from implementations. Your compiler can't check this for you. You need to read the docs, and do what they say. If you don't do what the contract says then you'll have an implementation of the interface as far as the compiler is concerned, but it will be a defective/invalid implementation.

在设计Collections API时,Joshua Bloch决定不使用非常精细的接口来区分不同的集合变体(例如:可读) ,可写,随机访问等)他只有非常粗糙的接口集,主要是
集合列表设置映射,然后将某些操作记录为可选。这是为了避免由细粒度界面引起的组合爆炸。来自 Java Collections API Design FAQ

When designing the Collections API Joshua Bloch decided that instead of having very fine-grained interfaces to distinguish between different variants of collections (eg: readable, writable, random-access, etc.) he'd only have very coarse set of interfaces, primarily Collection, List, Set and Map, and then document certain operations as "optional". This was to avoid the combinatorial explosion that would result from fine-grained interfaces. From the Java Collections API Design FAQ:


为了说明血腥细节中的问题,假设您要将
可修改性概念添加到层次结构中。您需要四个新的
接口:ModifiableCollection,ModifiableSet,ModifiableList和
ModifiableMap。以前简单的层次结构现在是一个混乱的
层次结构。此外,您需要一个新的Iterator接口,用于
不可修改的集合,它不包含remove操作。
现在你可以取消UnsupportedOperationException吗?不幸的是
没有。

To illustrate the problem in gory detail, suppose you want to add the notion of modifiability to the Hierarchy. You need four new interfaces: ModifiableCollection, ModifiableSet, ModifiableList, and ModifiableMap. What was previously a simple hierarchy is now a messy heterarchy. Also, you need a new Iterator interface for use with unmodifiable Collections, that does not contain the remove operation. Now can you do away with UnsupportedOperationException? Unfortunately not.

考虑数组。它们实现了大部分List操作,但不是
删除和添加。它们是固定大小的列表。如果要在层次结构中捕获
这个概念,则必须添加两个新接口:
VariableSizeList和VariableSizeMap。你不必添加
VariableSizeCollection和VariableSizeSet,因为它们是
与ModifiableCollection和ModifiableSet相同,但你可能会为了一致性而选择添加它们。此外,您需要一个新的
各种ListIterator,它不支持添加和删除
操作,以及不可修改的List。现在我们最多有10个或
12个接口,加上两个新的Iterator接口,而不是我们的
原始四个。我们完了吗?否。

Consider arrays. They implement most of the List operations, but not remove and add. They are "fixed-size" Lists. If you want to capture this notion in the hierarchy, you have to add two new interfaces: VariableSizeList and VariableSizeMap. You don't have to add VariableSizeCollection and VariableSizeSet, because they'd be identical to ModifiableCollection and ModifiableSet, but you might choose to add them anyway for consistency's sake. Also, you need a new variety of ListIterator that doesn't support the add and remove operations, to go along with unmodifiable List. Now we're up to ten or twelve interfaces, plus two new Iterator interfaces, instead of our original four. Are we done? No.

考虑日志(例如错误日志,审计日志和
可恢复数据对象的日记帐)。它们是自然的仅附加序列,
支持所有List操作,除了remove和set
(replace)。它们需要一个新的核心接口和一个新的迭代器。

Consider logs (such as error logs, audit logs and journals for recoverable data objects). They are natural append-only sequences, that support all of the List operations except for remove and set (replace). They require a new core interface, and a new iterator.

那么不可变的集合呢,而不是那些不可修改的集合呢?
(即客户无法更改的集合,并且绝不会因任何其他原因而变更
)。许多人认为这是所有人中最重要的
区别,因为它允许多个线程同时以
访问集合而无需同步。
将此支持添加到类型层次结构需要另外四个
接口。

And what about immutable Collections, as opposed to unmodifiable ones? (i.e., Collections that cannot be changed by the client AND will never change for any other reason). Many argue that this is the most important distinction of all, because it allows multiple threads to access a collection concurrently without the need for synchronization. Adding this support to the type hierarchy requires four more interfaces.

现在我们最多有二十个接口和五个迭代器,以及几乎可以肯定的是,实际
中仍然存在一些不完全适合任何接口的集合。例如,Map返回的
集合视图是自然删除集合。
此外,有些集合会拒绝
基础上的某些元素,因此我们仍然没有废除运行时
例外。

Now we're up to twenty or so interfaces and five iterators, and it's almost certain that there are still collections arising in practice that don't fit cleanly into any of the interfaces. For example, the collection-views returned by Map are natural delete-only collections. Also, there are collections that will reject certain elements on the basis of their value, so we still haven't done away with runtime exceptions.

当所有的事情都说完了之后,我们觉得通过提供一个非常小的
核心接口可以引发运行时异常来回避整个问题是一个合理的工程
折衷方案。

When all was said and done, we felt that it was a sound engineering compromise to sidestep the whole issue by providing a very small set of core interfaces that can throw a runtime exception.

当Collections API中的方法被记录为可选操作时,并不意味着你可以放弃方法在实现中实现,也不意味着你可以使用一个空方法体(一方面,其中许多需要返回一个结果)。相反,它意味着有效的实现选择(仍然符合合同的选择)是抛出 UnsupportedOperationException

When methods in the Collections API are documented as being "optional operations", it does not mean that you can just leave the method implementation out in the implementation, nor does it mean you can use an empty method body (for one thing, many of them need to return a result). Rather, it means that a valid implementation choice (one that still conforms to the contract) is to throw an UnsupportedOperationException.

请注意,因为 UnsupportedOperationException 是一个 RuntimeException 你可以就编译器而言,从任何方法实现中抛出它。例如,您可以从 Collection.size()的实现中抛出它。但是,这样的实现会违反合同,因为 Collection.size()的文档并未说明这是允许的。

Note that because UnsupportedOperationException is a RuntimeException you can throw it from any method implementation, as far as the compiler is concerned. For example, you could throw it from an implementation of Collection.size(). However, such an implementation would violate the contract as the documentation for Collection.size() does not say that this is permitted.

除此之外:Java的Collections API使用的方法有点争议(但现在可能比最初引入的时候少)。在完美的世界中,接口具有可选操作,而是使用细粒度接口。问题是Java既不支持推断的结构类型也不支持交集类型,这就是为什么尝试做事情,正确的方式最终变得非常难以收集。

Aside: The approach used by Java's Collections API is somewhat controversial (probably less now than when it was first introduced, however). In a perfect world, interfaces would not have optional operations, and fine grained interfaces would instead be used. The problem is that Java supports neither inferred structural types or intersection types, which is why attempting to do things the "right way" ends up becoming extremely unwieldy in the case of collections.

这篇关于Java接口中的可选方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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