关于私有化构造器(private constructor)

For me the best explanation is in Effective Java book: Item 4: Enforce noninstantiability with a private constructor (See more)

In Summary:

  • Private constructor is due utility classes were not designed to be instantiated, so is a design decision. (NO performance or memory overhead)
  • Making a class abstract doesn't work because can be subclassed and then instantiated.
  • With an abstract class the user may think the class is for inheritance.
  • The only way to ensure no instantiation is to add a private constructor which ensures the default constructor is not generated.
  • Private constructor prevents inheritance because the super constructor cannot be called (so it is not need the declare the class as final)
  • Throw an error in the private constructor avoids call it within the class.

Definetively, the best way would be something like next:

public class MyStrings {

     private MyStrings () {
       throw new AssertionError();
     }
      ... 
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值