《Cracking the Coding Interview》——第14章:Java——题目1
2024-10-18 08:30:54
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();
}
}
最新文章
- div实现自适应高度的textarea,实现angular双向绑定
- JSON字符串和对象 的转换
- (error) MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk
- GNU Radio Radar Toolbox
- .Net开源Excel、Word操作组件-NPOI、EPPlus、DocX[转]
- Unity调用Android方法
- 函数柯里化(Currying)示例
- markdownpad2使用说明
- localstorage 使用
- ubuntu 安装 flash player
- C# 课堂总结5-数组
- executeBatch()相关操作汇总
- bigdata之hadoop and spark
- jdk源码->;集合->;ArrayList
- WordPress菜单“显示选项”无法显示的解决办法
- Go学习——go+channel实战(转)
- 让公式在网页传播——mathJAX
- cmake 指定连接的opencv版本
- HDU 2058:The sum problem(数学)
- kafka-java客户端连接
热门文章
- Win10技巧:使用“照片”应用剪辑视频、添加特效
- windows 右健添加cmd快捷通道
- 模仿ArcGIS用Graphics重绘的直方图分级调节器
- IOS 设置颜色的的详情
- user(),current_user()函数的区别
- C# windows 计划任务 程序编写
- POJ-2718 Smallest Difference---DFS
- 【HHHOJ】ZJOI2019模拟赛(十五)03.17 解题报告
- 矩阵连乘的相乘次数(ZOJ1094)
- spring boot1.5.6 测试类