static 메서드들을 모아놓은 클래스는 기본적으로 인스턴스화를 시켜 사용하지 않는다.
우리가 Arrays를 사용할 때를 생각해보면 절대 Arrays arrays = new Arrays()로 생성하지 않고, Arrays.asList(배열)과 같은 형태로 사용하고 있다.
Arrays클래스를 실제로 열어보면 아래와 같다고 한다.
public class Arrays {
public static boolean isArray(Object o) { ...}
public static Object[] asObjectArray(Object array) { ...}
public static List<Object> asList(Object array) { ...}
public static <T> boolean isNullOrEmpty(T[] array) { ...}
// ...
private Arrays() {
}
}
- 메서드들이 모두 static으로 선언되어 있다.
- 생성자에 private 접근 제어를 선언하여 인스턴스로 초기화되지 못하게 막고 있다.
이와 같은 방식으로 유틸성 클래스를 생성하고 활용할 수 있게 된다.
[Final Class]
클래스에 final을 선언하면 상속을 금지한다는 뜻으로 사용한다.
대표적으로 String 클래스가 있다고 한다.
String의 여러기능을 마음대로 상속할 수 있게 해준다면 매우 혼란해질것이 자명하기 때문..
StringUtils도 비슷한 예제라고 한다.
@API(status = INTERNAL, since = "1.0")
public final class StringUtils {
private static final Pattern ISO_CONTROL_PATTERN = compileIsoControlPattern();
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s");
static Pattern compileIsoControlPattern() { ... }
private StringUtils() {
/* no-op */
}
public static boolean isBlank(String str) { ... }
public static boolean isNotBlank(String str) { ... }
public static boolean containsWhitespace(String str) { ... }
// ...
}
["Abstract Class + private 생성자" 조합으로 유틸성 클래스를 만들 순 없나?]
당연히 가능할 것이다. 왜냐면 abstract는 기본적으로 인스턴스로 선언할 수 없기 때문이다.
하지만 abstract 키워드가 애초에 클래스를 상속받아 추가구현하라는 걸 나타내기 때문에 목적자체가 다르다.
또한 하위클래스를 통해 상속받게되면 하위클래스는 인스턴스화할 수 있기 때문에 적절하지 않은 방법이라고 한다.
[결론]
유틸성 클래스를 만들려고 할때는 "final class 선언 + private 생성자 선언"을 통해 인스턴스화를 막는 것이 좋아보인다.
//MyStringUtil
//final을 통한 상속 불가 선언
public final class MyStringUtil {
public static int length(String str){
if(str==null){
return 0;
}
return str.length();
}
//private 생성자
private MyStringUtil() {
}
}
//main
public static void main(String[] args){
System.out.println(MyStringUtil.length("test"));
}
//실행결과
4
[참조]
[Java] 인스턴스화 방지를 위해 private 생성자 이용하기 (tistory.com)
[Java] 인스턴스화 방지를 위해 private 생성자 이용하기
정적 메소드, 정적 필드만 담은 클래스는 때때로 유용하게 쓰일 수 있다. 사용하는 경우가 크게 세 가지가 있는데 예제를 통해 살펴보자. 📕 1. 기본 타입 값이나 배열 관련 메소드를 모은 클래
yeonyeon.tistory.com
'Java' 카테고리의 다른 글
팩토리 메소드 디자인 패턴 (0) | 2022.11.26 |
---|---|
Windows 환경에 Zulu JDK 설치하기 (0) | 2022.11.20 |
throw, throws에 대한 정리 (0) | 2022.11.19 |
Checked Exception, UncheckedException (0) | 2022.11.14 |
ClassPath (클래스패스) 란? (0) | 2022.10.27 |