Difference between java enum with no values and utility class with private constructor

后端 未结 4 1883
日久生厌
日久生厌 2020-12-29 19:30

A common thing to do to utility classes is to give them a private constructor:

public final class UtilClass {
    private UtilClass() {}

    ...
}
         


        
4条回答
  •  长情又很酷
    2020-12-29 19:54

    The following pattern in utility classes also provides ironclad guarantee that there can be no instances:

    public abstract class Util {
        private Util() { throw new Error(); }
        ... // static methods
    }
    

    Besides, you have no additional irrelevant static methods, provided by enums.

提交回复
热议问题