[Java] [Read Effective Java] Chapter 2, Item 4 Force uninstantiable with private constructor

less than 1 minute read

Force non-instantiable with #private constructor

Utility classes (classes that consist of static methods and static fields) are not designed to be instantiated. Nevertheless, I often see things that can be instantiated, so let’s use a private constructor so that it can never be instantiated.

Glossary

Default constructor

When no constructor is defined, a constructor called default constructor is automatically created.

Sample code

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


// Utility class that cannot be instantiated
public class UtilityClass {
    // suppress default constructor to prevent instantiation
    private UtilityClass() {
        throw new AssertionError();
    }
     //Remaining omitted
}

Continue

[Read Effective Java] Chapter 2, Item 5 “Avoid creating unnecessary objects” https://qiita.com/Natsukii/items/ec64efddce85ffd59fa8