Private constructor in abstract class

后端 未结 7 1130
无人及你
无人及你 2020-12-31 05:54

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

7条回答
  •  旧时难觅i
    2020-12-31 06:42

    A final class with only private constructors is a design used by singletons and multitons.

    An abstract class which has only private constructors is the only way I've seen to prevent a class from being instantiated. I have seen it used to create utility classes (which only have static methods and/or members).

    As for setting up user expectations I see that https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html states "Abstract classes cannot be instantiated, but they can be subclassed." I note that it does not state any intention that they are expected to be subclassed.

    I also note however that viewing some Java source code I find the following designs are used (none of which are abstract classes with only private constructors):

    • Final utility classes with private constructors
      • http://developer.classpath.org/doc/java/lang/Math-source.html
      • http://developer.classpath.org/doc/java/lang/System-source.html
    • Final utility classes with private constructors which throw exceptions
      • http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Objects.java
    • Neither abstract nor final utility classes with private constructors
      • http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/ArrayPrefixHelpers.java
      • http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Arrays.java
      • https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Collections.java
      • http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/FormattableFlags.java
    • Looks like a utility, but apparently can be instantiated (no private constructors)
      • http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/ArraysParallelSortHelpers.java

提交回复
热议问题