抽象类中的私有构造函数 [英] Private constructor in abstract class
问题描述
在Java中,在抽象类中使用私有构造函数的目的是什么?
In Java what is the purpose of using private constructor in an abstract class?
在评论中我遇到了这个问题,我很好奇,在什么情况下我们需要以这种方式使用构造函数?
In a review I got this question, and I am curious, for what situation we need to use the constructor in such way?
我认为它可以与抽象类中的另一个构造函数一起使用,但这非常简单。也可以用于构造将超过抽象类的静态内部类。
I think it can be used in pair with another constructor in abstract class, but this is very trivial. Also it can be used for constructing static inner classes which will excend abstract class.
也许还有更优雅的用法?
Maybe there is more elegant usage?
推荐答案
如果 private
构造函数是该类的 only 构造函数,则原因很明显:防止子类化。一些类仅充当静态字段/方法的持有者,而不希望被实例化或子类化。请注意,在这种情况下,抽象
修饰符是多余的—,没有或没有它的实例化。就像@JB Nizet在下面指出的那样,抽象
修饰符也是不好的做法,因为它向班级的客户发送错误的信号。实际上,该类应该是 final
。
If the private
constructor is the only constructor of the class, then the reason is clear: to prevent subclassing. Some classes serve only as holders for static fields/methods and do not want to be either instantiated or subclassed. Note that the abstract
modifier is in this case redundant—with or without it there would be no instantiation possible. As @JB Nizet notes below, the abstract
modifier is also bad practice because it sends wrong signals to the class's clients. The class should in fact have been final
.
还有另一个用例,尽管很少见:您可以抽象类
,其中只有私有
构造函数,其包含自己的子类作为嵌套类。这个习语可确保这些嵌套类是唯一的子类。实际上,Java中的 enum
s只是使用这个惯用法。
There is another use case, quite rare though: you can have an abstract class
with only private
constructors that contains its own subclasses as nested classes. This idiom makes sure those nested classes are the only subclasses. In fact, enum
s in Java use just this idiom.
如果周围还有其他构造函数,那么 private
构造函数真的没什么特别的。就像在其他任何类中一样,它在抽象
类中使用。
If there are other constructors around, well then there's really nothing special about the private
constructor. It gets used in an abstract
class just as in any other.
这篇关于抽象类中的私有构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!