Java 17에서 추가된 sealed Class에 대해서 알아보자. sealed 클래스는 상속을 허용하기 위한 용도로 사용된다. sealed 클래스로 선언된 클래스는 해당 클래스를 상속을 할 수 있도록 허용된 특정 클래스들만 상속이 가능하다.
아래 예시를 살펴보면 이해가 쉬울 것이다.
public sealed class Cloth permits Shirts {
static int stock; // 재고
private int cost; // 가격
private String size; // 사이즈
private String texture; // 재질
// getter, setter 생략
public boolean sell() {
if(stock == 0) return false;
stock--;
return true;
}
}
permits Shirts라는 부분에 주목하자. Shirts라는 클래스만이 Cloth 클래스를 상속받을 수 있다는 의미이다.
뒤에 ,(콤마)를 붙여서 여러 개의 클래스들이 상속 받을 수 있도록 하는 것도 가능하다.
public sealed class Cloth permits Shirts, Hoodie { // Hoodie가 추가됨
static int stock; // 재고
private int cost; // 가격
private String size; // 사이즈
private String texture; // 재질
// getter, setter 생략
public boolean sell() {
if(stock == 0) return false;
stock--;
return true;
}
}
sealed 클래스 선언을 위해 지켜야 할 규칙은 아래와 같다.
즉, 위의 규칙들에 의해 Shirts 클래스는 아래 중 하나의 경우로 선언이 되어야한다.
public sealed class Shirts extends Cloth permits BlueShirts, WhiteShirts{
// 내용은 생략
}
public final class Shirts extends Cloth {
// 내용은 생략
}
public non-sealed class Shirts extends Cloth {
// 내용은 생략
}
이렇게 non-sealed 클래스로 만들면 아무 클래스나 확장이 가능하기 때문에 주의해야한다.
당연한 이야기일 수 있겠지만, sealed 클래스를 abstract class로 선언하는 것도 가능하다. abstract 클래스란 abstract 메소드를 하나 이상 포함한 클래스를 의미한다.
public abstract sealed class Cloth permits Shirts{ // abstract으로 선언
static int stock; // 재고
private int cost; // 가격
private String size; // 사이즈
private String texture; // 재질
// getter, setter 생략
public boolean sell() {
if(stock == 0) return false;
stock--;
return true;
}
// 옷의 설명을 출력하는 추상 메소드
public abstract void printDetail();
}
public final class Shirts extends Cloth {
@Override
public void printDetail() {
System.out.println("예쁜 셔츠입니다~");
}
}
public class Main {
public static void main(String[] args) {
Cloth shirts = new Shirts();
shirts.printDetail();
}
}
sealed 클래스는 특정 클래스들을 제외한 다른 것들의 상속을 막아주기 때문에, 특정 도메인의 내용만 담고 있는 클래스를 만들 때 유용하게 쓸 수 있다.
예를 들어 위 예제처럼 Cloth라는 클래스를 만들고 옷과 관련된 필드와 메소드를 선언했는데 뜬금 없이 Chair라는 가구 클래스가 Cloth를 확장하면 안될 것이다. 이럴 때에는 안되는 클래스들을 제한하는 것보다 되는 클래스들을 허용해주는 편이 쉽기 때문에 sealed 클래스가 등장한 것 같다.
책 자바의 신2 p.420~424
https://www.baeldung.com/java-sealed-classes-interfaces
https://velog.io/@sweet_sumin/Sealed-class-%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%BC%EA%B9%8C