본문 바로가기

Language/Java

[Effective Java] Item4.

Item4. Enforce noninstantiability with a private constructor 





- factory method로 static method들을 그룹화할 수 있다.(item 1)

- Utility class들은 instance로 만들어 지기 위해 설계되지 않는다.  

- 그러나 명시적인 생성자가 없으면 compiler가 default 생성자를 만들어준다. 



# attempting to enforce noninstantiability 

 if) by making a class abstract 

  - 문제점 : 해당 클래스가 상속을 위한 것으로 오해할 수도 있다. 

  - 문제점 : subclass가 만들어질 수 있고 해당 subclass가 인스턴스화 될 수 있다. 

  


- 생성자가 없으면 compiler가 default 생성자를 넣어서 instance화 할 수 있게 되기 때문에, private constructor를 통해 instance 생성을 막는다. 

- private constructor로 인하여 외부에서 해당 클래스를 접근할 수 없다. 

- 또한, private constructor를 의도적으로 넣음으로써 subclass화를 막을 수 있다. 

- 모든 생성자는 명시적이건 암시적이건 superclass의 constructor를 호출한다. 

'Language > Java' 카테고리의 다른 글

[Effective Java] Item 3  (0) 2017.01.14
[Effective Java] item 2  (0) 2016.12.20
[Effective Java] item 1  (0) 2016.12.19
attach source javadoc in eclipse  (0) 2015.02.11