private constructor and final
W开发者_开发问答hy is it a good practice to mark a class with only private constructors as final? My guess is, it is to let other programmers know that it cannot be sub-classed.
It is often considered (e.g. by Josh Bloch and the designers of C#) good practice to mark everything as final unless you have an explicit reason not to. Assuming you mean class, you're correct that a class with only private constructors can't be subclassed. Thus, the final could be considered redundant, but as you say it has value for documentation. As Marc suggests, it may also aid optimization.
Making a class final has some (small) performance gain, because the JIT compiler can inline functionality from that class. I don't know if that qualifies as 'good practice', but I see the advantages.
You mean "a class with private constructor" do you?
A final class can't be subclassed. This may represent a design decision. Not all classes are designed to be subclassed, so if yours is not, it is best to mark it explicitly, to avoid subtle bugs later.
A class with private constructors only can't be instantiated by the outside world (neither subclassed). This may be useful for e.g. singletons, or classes where you want to control what instances of the class are created. E.g. before Java5, the typesafe enum pattern used this.
We mark the class as final class by making constructor as private, to avoid sub-classing.
This is good practice, in cases where we don’t want people to override our class methods and change the functionality or add the functions to our class.
For example, classes String and Math are final classes, which we can’t extend or subclass, this is to make sure that no one will change their behavior.
A final class with private constructor:
- Class can not have sub-classes, we can not extent final class.
- Class having private constructor, we can not create the object of that class.
It means other methods of the class will be static, so that class can access them.
精彩评论