2014-04-26 18:20

题目:从继承的角度,把构造函数设成private有什么意义?

解法:就不能继承了。单体模式里也这么干,目的是为了不让使用者自主生成对象,进行限制。

代码:

 // 14.1 In terms of inheritance, what is the point of declaring the constructor as private?
// Answer:
// 1. private member cannot be inherited, thus the class cannot be inherited.
// 2. constructor is private, so you cannot new an object freely. Only through public static member method can you get an instance of this class.
// 3. with this you can implement Singleton Pattern, which ensures that a class has at most one instance within an application. You can but you don't have to do it.
public class TestJava {
private static TestJava instance = null; public static TestJava getInstance() {
if (instance == null) {
instance = new TestJava();
}
return instance;
} public void f() {
System.out.println("TestJava::f()");
} private TestJava() {
} public static void main(String[] args) {
System.out.println("Hello world.");
TestJava testJava = TestJava.getInstance();
testJava.f();
}
}

最新文章

  1. div实现自适应高度的textarea,实现angular双向绑定
  2. JSON字符串和对象 的转换
  3. (error) MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk
  4. GNU Radio Radar Toolbox
  5. .Net开源Excel、Word操作组件-NPOI、EPPlus、DocX[转]
  6. Unity调用Android方法
  7. 函数柯里化(Currying)示例
  8. markdownpad2使用说明
  9. localstorage 使用
  10. ubuntu 安装 flash player
  11. C# 课堂总结5-数组
  12. executeBatch()相关操作汇总
  13. bigdata之hadoop and spark
  14. jdk源码->集合->ArrayList
  15. WordPress菜单“显示选项”无法显示的解决办法
  16. Go学习——go+channel实战(转)
  17. 让公式在网页传播——mathJAX
  18. cmake 指定连接的opencv版本
  19. HDU 2058:The sum problem(数学)
  20. kafka-java客户端连接

热门文章

  1. Win10技巧:使用“照片”应用剪辑视频、添加特效
  2. windows 右健添加cmd快捷通道
  3. 模仿ArcGIS用Graphics重绘的直方图分级调节器
  4. IOS 设置颜色的的详情
  5. user(),current_user()函数的区别
  6. C# windows 计划任务 程序编写
  7. POJ-2718 Smallest Difference---DFS
  8. 【HHHOJ】ZJOI2019模拟赛(十五)03.17 解题报告
  9. 矩阵连乘的相乘次数(ZOJ1094)
  10. spring boot1.5.6 测试类