[Java] Pattern Matching for instanceof

윤석진·2021년 11월 23일
0
post-thumbnail

Pattern Matching for instanceof

instanceof에서 객체 타입 확인뿐만 아니라 캐스팅까지 할 수 있다.

Release

  • JDK 14: preview
  • JDK 15: second preview
  • JDK 16

JEP 394 Pattern Matching for instanceof

코드로 비교해보자

Before

if (animal instanceof Cat) {
    Cat cat = (Cat) animal;
    cat.meow();
} else if (animal instanceof Dog) {
    Dog dog = (Dog) animal;
    dog.woof();
}

instanceof를 이용해 객체 타입을 확인하고 추가로 캐스팅을 해줘야 했다.

After

if (animal instanceof Cat cat) {
    cat.meow();
} else if(animal instanceof Dog dog) {
    dog.woof();
}

instanceof에서 객체 타입 확인과 캐스팅을 한번에 해결할 수 있다.

profile
공부하며 쓰는 블로그

0개의 댓글