File: PrivateConstructorForUtilityClass.md

package info (click to toggle)
error-prone-java 2.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 23,204 kB
  • sloc: java: 222,992; xml: 1,319; sh: 25; makefile: 7
file content (23 lines) | stat: -rw-r--r-- 767 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Utility classes are classes that only include static members and are not
designed to be instantiated, for example `java.lang.Math` or `java.util.Arrays`.

In the absence of explicit constructors, however, the compiler provides a
public, parameterless default constructor. To a user, this constructor is
indistinguishable from any other. It is not uncommon for a published API to
accidentally include a public constructor for a class intended to be
uninstantiable.

To prevent users from instantiating classes that are not designed to be
instantiated, you can add a private constructor:

```java
public class UtilityClass {
  private UtilityClass() {}
}
```

See:

*   [Effective Java 3rd Edition ยง4][ej3e-4]

[ej3e-4]: https://books.google.com/books?id=BIpDDwAAQBAJ