抽象类中的私有构造函数 [英] Private constructor in abstract class

查看:38
本文介绍了抽象类中的私有构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,在抽象类中使用私有构造函数的目的是什么?

In Java what is the purpose of using private constructor in an abstract class?

在review中我得到了这个问题,我很好奇,在什么情况下我们需要以这种方式使用构造函数?

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 构造函数是类的唯一构造函数,那么原因很清楚:防止子类化.某些类仅用作静态字段/方法的持有者,并且不想被实例化或子类化.请注意,abstract 修饰符在这种情况下是多余的——无论有没有它,都不可能进行实例化.正如@JB Nizet 在下面指出的那样, abstract 修饰符也是不好的做法,因为它会向类的客户端发送错误的信号.该类实际上应该是 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.

还有另一个用例,虽然非常罕见:您可以拥有一个 抽象类,其中只有 private 构造函数,该构造函数包含自己的子类,如嵌套类.这个习惯用法确保那些嵌套的类是唯一的子类.事实上,Java 中的 enum 就使用了这个习惯用法.

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, enums in Java use just this idiom.

如果周围还有其他构造函数,那么 private 构造函数真的没有什么特别之处.它可以在 abstract 类中使用,就像在任何其他类中一样.

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屋!

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