2014-04-26 18:20
题目:从继承的角度,把构造函数设成private有什么意义?
解法:就不能继承了。单体模式里也这么干,目的是为了不让使用者自主生成对象,进行限制。
代码:
1 // 14.1 In terms of inheritance, what is the point of declaring the constructor as private? 2 // Answer: 3 // 1. private member cannot be inherited, thus the class cannot be inherited. 4 // 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. 5 // 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. 6 public class TestJava { 7 private static TestJava instance = null; 8 9 public static TestJava getInstance() { 10 if (instance == null) { 11 instance = new TestJava(); 12 } 13 return instance; 14 } 15 16 public void f() { 17 System.out.println("TestJava::f()"); 18 } 19 20 private TestJava() { 21 } 22 23 public static void main(String[] args) { 24 System.out.println("Hello world."); 25 TestJava testJava = TestJava.getInstance(); 26 testJava.f(); 27 } 28 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)