Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

private constructor and final

Tags:

java

Why 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.

like image 359
rest_day Avatar asked Jun 02 '10 09:06

rest_day


People also ask

Can constructor be private and final in Java?

Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class.

What is the difference between private and final?

private is about accessibility like public or protected or no modifier. final is about modification during inheritance. private methods are not just accessible from the outside of the class. final methods can not be overridden by the child class.

Can a final class have a constructor?

No, a constructor can't be made final. A final method cannot be overridden by any subclasses. As mentioned previously, the final modifier prevents a method from being modified in a subclass. The main intention of making a method final would be that the content of the method should not be changed by any outsider.

What happens if constructor is private?

A private constructor in Java is used in restricting object creation. It is a special instance constructor used in static member-only classes. If a constructor is declared as private, then its objects are only accessible from within the declared class. You cannot access its objects from outside the constructor class.


1 Answers

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.

like image 72
Matthew Flaschen Avatar answered Oct 01 '22 21:10

Matthew Flaschen