为什么选择< T>宣布为最后一堂课? [英] Why is Optional<T> declared as a final class?
问题描述
我正在玩以下问题:使用Java 8的可选流程:: flatMap 并希望将方法添加到自定义可选< T>
,然后检查它是否有效。
更准确,我想要将 stream()
添加到我的 CustomOptional< T>
,如果没有值,则返回空流,或者如果它存在,则包含单个元素的流。
I was playing with the following question: Using Java 8's Optional with Stream::flatMap and wanted to add a method to a custom Optional<T>
and then check if it worked.
More precise, I wanted to add a stream()
to my CustomOptional<T>
that returns an empty stream if no value is present, or a stream with a single element if it is present.
然而,我得出的结论是可选< T>
被宣布为最终。
However, I came to the conclusion that Optional<T>
is declared as final.
为什么会这样?有很多类没有被声明为final,我个人认为没有理由声明 Optional< T>
final。
Why is this so? There are loads of classes that are not declared as final, and I personally do not see a reason here to declare Optional<T>
final.
作为第二个问题,为什么所有的方法都不能是最终的,如果担心它们会被覆盖,并且让这个课程不是最终的?
As a second question, why can not all methods be final, if the worry is that they would be overridden, and leave the class non-final?
推荐答案
根据这个Java SE 8 API文档的页面,可选< T>
是一个基于值的类。根据 API文档的此页面,基于值的类必须是不可变的。
According to this page of the Java SE 8 API docs, Optional<T>
is a value based class. According to this page of the API docs, value-based classes have to be immutable.
声明中的所有方法可选< T>
作为final将阻止方法被覆盖,但这不会阻止扩展类添加字段和方法。扩展类并添加字段以及更改该字段值的方法将使该子类可变,因此将允许创建可变的可选< T>
。以下是如果 Optional< T>
不会被声明为final的话,可以创建这样一个子类的示例。
Declaring all the methods in Optional<T>
as final will prevent the methods from being overridden, but that will not prevent an extending class from adding fields and methods. Extending the class and adding a field together with a method that changes the value of that field would make that subclass mutable and hence would allow the creation of a mutable Optional<T>
. The following is an example of such a subclass that could be created if Optional<T>
would not be declared final.
//Example created by @assylias
public class Sub<T> extends Optional<T> {
private T t;
public void set(T t) {
this.t = t;
}
}
声明可选< T>
final会阻止创建类似上面的子类,因此保证 Optional< T>
始终是不可变的。
Declaring Optional<T>
final prevents the creation of subclasses like the one above and hence guarantees Optional<T>
to be always immutable.
这篇关于为什么选择< T>宣布为最后一堂课?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!