[Read Effective Java] Chapter 2 Item 4 "Force uninstantiation with a private constructor"

Force non-instantiation with private constructor

Utility classes (classes consisting of static methods and static fields) are not designed to be instantiated. Despite this, I often see things that can be instantiated, so let's use a private constructor to make it absolutely impossible to instantiate.

Glossary

Default constructor

If no constructor is defined, a constructor called the default constructor is automatically created.

Sample code

By explicitly writing a private constructor, access from the outside is disabled and the generation of the default constructor is suppressed. AssertionError is not strictly necessary, but it is insured.


//Utility classes that cannot be instantiated
public class UtilityClass {
    //Suppress the default constructor to prevent instantiation
    private UtilityClass() {
        throw new AssertionError();
    }
    … //The rest is omitted
}

Continue

[Read Effective Java] Chapter 2 Item 5 "Avoid the creation of unnecessary objects" https://qiita.com/Natsukii/items/ec64efddce85ffd59fa8

Recommended Posts

[Read Effective Java] Chapter 2 Item 4 "Force uninstantiation with a private constructor"
[Read Effective Java] Chapter 2 Item 3 "Force singleton characteristics with private constructor or enum type"
Force non-instantiation with Effective Java private constructor
[Read Effective Java] Chapter 2 Item 2 "Consider a builder when faced with a large number of constructor parameters"
[Read Effective Java] Chapter 2 Item 7 "Avoid Finalizers"
[Read Effective Java] Chapter 3 Item 10 "Always Override toString"
[Read Effective Java] Chapter 3 Item 12 "Considering Implementation of Comparable"
[Read Effective Java] Chapter 2 Item 6 "Remove obsolete object references"
[Read Effective Java] Chapter 3 Item 9 "When overriding equals, always override hashCode"
[Read Effective Java] Chapter 2 Item 5 "Avoid the creation of unnecessary objects"
[Read Effective Java] Chapter 2 Item 1 "Consider static factory methods instead of constructors"
[Read Effective Java] Chapter 3 Item 8 "When overriding equals, follow the general contract"
Effective Java Chapter 2
Effective Java Chapter 6 34-35
Effective Java Chapter 4 15-22
Effective Java Chapter 3
Read a string in a PDF file with Java
Effective Java Item 25 Select a list from an array First half
Build a Java project with Gradle
Effective Java 3rd Edition Chapter 5 Generics
Effective Java 3rd Edition Chapter 8 Methods
[Java] Test private methods with JUnit