본문 바로가기

Web/JAVA

[Java 17] 특징 및 예제 코드

728x90

 

 

블로그 참조 + 예제코드를 내 것처럼 만들어서 따라해보기

 

 

 

 

 

1. record (from java 14)

 

record 는 간결하고 변경 불가한 객체 타입이다

 

 

public class Test {

	private String name;
    private int numbering;
    
    
    public Test(String name, int numbering){
    	this.name = name;
        this.numbering = numbering;
    }
    
    getter..
    setter..
    toString..
    equals..
    hashCode..
}

 

public record Test(String name, int numbering){}

record

불변객체로 setter method가 없음

toString, equals, hashCode 자동 생성

 

 

 

 

2. sealed ~ permits

 

sealed 키워드를 사용하여 interface를 Implement 하는 클래스에 permit을 걸 수 있다

 

sealed interface Shape permits Circle, Square, Rectangle {
    int getArea();
}
final class Circle implements Shape {
    int radius;
    Circle(int radius) {
        this.radius = radius;
    }
    public int getArea() {
        return (int) (Math.PI * radius * radius);
    }
}
final class Square implements Shape {
    int side;
    Square(int side) {
        this.side = side;
    }
    public int getArea() {
        return side * side;
    }
}
final class Rectangle implements Shape {
    int width, height;
    Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }
    public int getArea() {
        return width * height;
    }
}

sealed 인터페이스에서 permits 에 명시된 클래스만 implement 할 수 있게 제한을 걸어준다

 

 

 

 

3. Text Blocks

\n 에서 해방 ㅎ_ㅎ

String html = """
    <html>
        <body>
            <p>Hello, World!</p>
        </body>
    </html>
""";

 

 

 

4. Pattern Matching

Java의 모든 객체는 Object 를 상속받습니다. Object객체의 타입을 switch에서 구분햘 수 있습니다.

Object obj = ...;
switch (obj) {
    case 0:
        System.out.println("zero");
        break;
    case String s:
        System.out.println(s.length());
        break;
    case int i:
        System.out.println(i);
        break;
    default:
        System.out.println("unknown");
}
728x90

'Web > JAVA' 카테고리의 다른 글

데이터 구조  (1) 2023.10.19
[Java Stream] skip() vs limit()  (0) 2023.04.23
[Java 17] 알아보기  (0) 2023.04.22
[Java LTS] Java 8, 11, 17  (0) 2023.04.22
[Stream]  (0) 2023.04.19