-
Item 4: Enforce noninstantiability with a private constructor독서/Effective Java 2021. 12. 4. 19:48
Private 생성자로 비인스턴스화를 강제하자.
정적 메서드와 정적 필드만을 담은 유틸리티 클래스는 객체 지향과 거리도 멀지만 유효성 체크, 패턴 매칭, UUID 검증 등 쓰임새가 있다.
정적 메서드와 정적 필드만을 담은 클래스의 예시
- java.lang.Math, java.util.Arrays
- java.util.Collections
특정 인터페이스를 구현하는 객체를 생성해주는 정적 메서드(혹은 팩터리) 모음 - final 클래스와 관련한 메서드들의 모음
(final 클래스를 상속해 하위 클래스에 메서드를 넣는 건 불가능하기 때문)
이와 같이 정적 멤버, 메소드만 존재하는 클래스의 경우 인스턴스화해서 사용하는 것이 아닌, 변하지 않고 사용되는 공용 클래스로 사용된다. 하지만, 생성자를 명시하지 않으면 컴파일러가 자동으로 기본 생성자(매개변수 없는 public)를 만들어준다.
인스턴스화 막기
Abstract Class로 생성하는 것만으로는 비인스턴스화를 강제할 수 없다.
하위 클래스를 만들어 인스턴스화 하면 적용된다.
만약 내가 Abstract Class를 본 사용자라면 상속해서 쓰라는 것으로 생각하게 될 것이다.private 생성자를 추가하면 클래스의 인스턴스화를 막을 수 있다.
인스턴스를 만들 수 없는 유틸리티 클래스는 다음과 같이 만들 수 있다.
public class Strings { private static String INPUT_ERROR_CAR_FULL_NAMES = "입력된 차량들의 전체 이름이 잘못 되었습니다."; private Strings() { } public static boolean checkNotNullOrNotEmpty(String str) { return str != null && !str.trim().isEmpty(); } public static void isValidCarNames(String carNames) { if (!Strings.checkNotNullOrNotEmpty(carNames)) { throw new IllegalArgumentException(INPUT_ERROR_CAR_FULL_NAMES); } } }
명시적 생성자가 private이기 때문에 밖에서 해당 클래스를 생성할 수 없다. 따라서, 어떤 환경에서도 클래스가 인스턴스화될 수 없다.
또한, private으로 생성자를 선언했기 때문에 상속이 불가능하다. 고로, 하위 클래스에서 상위 클래스에 접근할 수 없다.'독서 > Effective Java' 카테고리의 다른 글
Item 6: Avoid creating unnecessary objects (0) 2021.12.04 Item 5: Prefer dependency injection to hardwiring resources (0) 2021.12.04 Item 3: Enforce the singleton property with a private constructor or an enum type (0) 2021.12.04 Item 2: Consider a builder when faced with many constructor parameters (0) 2021.12.04 Item 1. Consider static factory methods instead of constructors (0) 2021.12.04