随笔- 509  文章- 0  评论- 151  阅读- 22万 

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 }
复制代码

 

 posted on   zhuli19901106  阅读(341)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示