来自 Effective Java 的第 4 章给出了以下示例:
public class Complex {
private final double re;
private final double im;
private Complex(double re, double im) {
this.re = re;
this.im = im;
}
public static Complex valueOf(double re, double im) {
return new Complex(re, im);
}
... // Remainder unchanged
}
[...] It is the most flexible because it allows the use of multiple package-private implementation classes. To its clients that reside outside its package, the immutable class is effectively final because it is impossible to extend a class that comes from another package and that lacks a public or protected constructor.
我知道这个类实际上是 final
,
但不将其声明为 final
是否有任何实际优势?
当类不支持扩展时省略此关键字似乎是一种不太明确的方式来传达 API
的用途。还是 final
只是为了向读者展示不可扩展的、非 final 类是可能的?
最佳答案
主要的好处是限制了继承的范围。将其声明为 final
将使它在任何地方都被密封;然而,有时作为类的作者,您希望继承同一个包或类文件中的 class
,但您不希望其他人也这样做。这就是这个技巧的作用。
更改一个开放继承的类(常用API)是一场噩梦。如果可以限制继承的范围,那么它就变成了一个简单的重构工作。
关于java - 有效的 Java : Make constructors private or package-private,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36064334/