M
M
Mimocodil2021-04-29 17:19:57
Java
Mimocodil, 2021-04-29 17:19:57

Why do finalized classes in java sources have private constructors?

In the course of learning the language, I discovered the source codes and plunged headlong into them. Now I'm looking at the Math class and StrictMath. I noticed that both (and many others) have a private constructor and an interesting comment.

/*
 * Don't let anyone instantiate this class.
 */
private Math() {}


Why did they do it? Why is creating an instance of, for example, the StrictMath class bad?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Zagaevsky, 2021-04-29
@Ezekiel4

Because these classes are not classes in general. They are made classes solely due to the fact that in Java you cannot write any code outside the class. These utility classes are essentially namespaces for pure functions (static methods). It is pointless to create their instances, and therefore it is forbidden.

M
Mercury13, 2021-04-29
@Mercury13

Nothing special. It's just that library functions protect against "abnormal" use more strongly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question