《Cracking the Coding Interview》——第14章:Java——题目1

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 }

 

你可能感兴趣的:(interview)