转载

Effective Java 04 Enforce noninstantiability with a private constructor

A class can be made noninstantiable by including a private constructor.

// Noninstantiable utility class

public class UtilityClass {

// Suppress default constructor for noninstantiability

private UtilityClass() {

throw new AssertionError();

}

... // Remainder omitted

}

Advantage

This explicitly prevents the user to instantiate the class.

Disadvantage

The class cannot be subclassed.

转载于:https://www.cnblogs.com/haokaibo/p/enforce-noninstantiability-with-a-private-constructor.html

正文到此结束
本文目录