https://stackoverflow.com/a/7486111/17273668 ; from what I have seen here to make a class "static" , we have to make it final with private constructor and static fields and methods.
Is there any difference between making the constructor private and making the class abstract?
CodePudding user response:
There is a huge difference between making a constructor private, or making a class abstract. Making a constructor private means that the constructor can only be invoked within the class itself or its nested classes, which means it cannot be called from outside. Making a class abstract means that it can only be instantiated by subclassing it. If a class is abstract, but has a non-private constructor (the default constructor is public), it means it can be subclassed by classes in other compilation units.
When it comes to utility classes, making the class final with a private constructor is - in my opinion - the better choice. The alternative is to make it abstract with a private constructor, but I think that is abusing the term abstract. Making something abstract raises an expectation of having concrete subclasses, which is not what you do with a utility class.
CodePudding user response:
An abstract
class can be extended by sub classes, a private constructor (if it is the only constructor) prevents sub-classing (exception: nested classes). The only way to instantiate a class with private constructor is by implementing a static factory method in the class itself (e.g. Optional.of
).