This is an old revision of the document!
여러 줄에 걸친 문자열을 만들기 위한 새로운 문법
12에서 preview였다가 15에서 정식 기능으로 승격
// """ 다음으로 문자가 올 수 없고, 한줄로 작성할 수 없다! // \를 사용하면 개행 제거 // 들여쓰기도 가능 String str = """ A BC DEF"""
12에서 preview였다가 14에서 정식 기능으로 승격
private String calculateTestGrade1(int score) {
return switch (score) {
case 5:
yield "A";
case 4, 3:
yield "B";
case 2:
yield "C";
default:
yield "F";
};
}
private String calculateTestGrade2(int score) {
return switch (score) {
case 5 -> "A";
case 4, 3 -> "B";
case 2 -> {
System.out.println("C!");
yield "C";
}
default -> "F";
};
}
14에서 preivew였다가 16에서 정식 기능으로 승격
public String say(Animal animal) throws IllegalAccessException {
if (animal instanceof Dog dog) {
return dog.bark();
} else if (animal instanceof Cat cat) {
return cat.purr();
}
throw new IllegalAccessException();
}
// 아래처럼 부정인 경우 Scope가 괄호 밖까지 확장 가능
public String sayIfDog(Animal animal) throws IllegalAccessException {
if (!(animal instanceof Dog dog)) {
throw new IllegalAccessException();
}
return dog.bark();
}
public interface Animal {
}
public static class Dog implements Animal {
public String bark() {
return "Dog barking...";
}
}
public static class Cat implements Animal {
public String purr() {
return "Cat purring...";
}
}
데이터 전달을 위한 클래스 (DTO) → Lombok 기능을 대체
14에서 preivew였다가 16에서 정식 기능으로 승격
public record PersonDtoV1 (
String name,
int age
) {
// Compact Constructor. 매개변수를 전혀 받지 않는다. this를 사용하지 않는다. (매개변수가 있다고 가정)
/*public PersonDtoV1 {
}*/
}
하위 클래스를 지정된 클래스로만 상속을 제한(봉인)
자바 15에서 preview였다가 17에서 정식 기능으로 승격
// 한 파일에 있다면 permits 생략 가능
public sealed interface Animal permits Dog, Cat {
}
// final : 재상속 불가능
// sealed : 한 번더 sealed class로 동작
// non-seald : 상속 가능하지만 하위 타입 추적 불가능
public final static class Dog implements Animal {
public String bark() {
return "Dog barking...";
}
}
public final static class Cat implements Animal {
public String purr() {
return "Cat purring...";
}
}