더북(TheBook)

instanceof 검사가 적절한 상황이 하나 있다. 바로 동등성 개념이 슈퍼클래스에 고정되어 있으면서 서브클래스에서 절대 변하지 않을 때다. 예를 들어 직원을 ID로 비교하는 상황을 생각해 보자. 이때는 instanceof로 검사하고 equals 메서드를 final로 선언하면 된다.

public class Employee {

    private int id;

    ...

    public final boolean equals(Object otherObject) {

        if (this = = otherObject) return true;

        if (!(otherObject instanceof Employee)) return false;

        Employee other = (Employee) otherObject;

        return id = = other.id;

    }


    public int hashCode() { ... }

}

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.