SSISO Community

시소당

instanceof가 혼란스럽게 느껴질 수 있는 이유

Tricky instanceof operator는 흥미로운 예제이다. 스터디의 관련 발표에서 민재님은 instanceof 대신 getClass()를 쓸 수 있음을 얘기한 바 있다. 다만, 용도가 다른 것이니까 분명하게 구분할 필요가 있다.


위 그림과 같이 상속이 전제된 상황이라면
class Poly extends Super implements Contract

다음과 같이 하나의 객체가 다수의 타입을 지닐 수 있다.
 Poly poly = new Poly();
 assertTrue(poly instanceof Poly);
 assertTrue(poly instanceof Super);
 assertTrue(poly instanceof Object);
 assertTrue(poly instanceof Contract);

다형성(Polymorphism)은 분명한 장점이지만, 이를 쓰기 위해서는 다층적(layered) 혹은 다차원의(multi-dimensional) 사고를 요구한다.

정확한 클래스를 알고자 할 경우는 getClass()를 활용한다.
 assertEquals(poly.getClass(), Poly.class);
 assertNotSame(poly.getClass(), Super.class);
 assertNotSame(poly.getClass(), Object.class);
 assertNotSame(poly.getClass(), Contract.class);

825 view

4.0 stars