rest_day
rest_day

Reputation: 858

private constructor and final

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.

Upvotes: 12

Views: 8252

Answers (5)

AKT
AKT

Reputation: 172

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.

Upvotes: 1

sap
sap

Reputation: 679

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.

Upvotes: 2

Matthew Flaschen
Matthew Flaschen

Reputation: 285077

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.

Upvotes: 14

Péter Török
Péter Török

Reputation: 116306

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.

Upvotes: 4

Marc
Marc

Reputation: 3560

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.

Upvotes: 6

Related Questions