반응형
■ instanceof 연산자(예약어)
-. instanceof 연산자가 기호로 되어 있지 않은 연산자이다.
-. instanceof 연산자는 유일하게 자바의 예약어로 되어 있는 연산자가 바로 instanceof 연산자다.
배열의 타입이 Child인지 Parent인지 어떻게 구분해야 하는 경우 사용하는 것이 instanceof라는 예약어이다.
public class Inheritance { // 중간생략 public void objectCast2() { Parent[] parentArray = new Parent[3]; parentArray[0] = new Child(); parentArray[1] = new Parent(); parentArray[2] = new Child(); for (Parent tempParent:parentArray) { if(tempParent instanceof Child) { System.out.println("Child"); } else if(tempParent instanceof Parent) { System.out.println("Parent"); } } } } |
-. instanceof의 앞에는 객체를, 뒤에는 클래스(타입)를 지정해 주면 된다. 그러면 이 문장은 true나 false와 같이 boolean 형태의 결과를 제공한다.
-. parentArray의 0번째 값은 Child 클래스의 객체이므로, [0] 값은 첫번째 if 문에서 true, [1] 값은 두번째 if 문에서 true, [2] 값은 첫번째 if 문에서 true여야 한다.
※ 컴파일 결과
Child Parent Child |
반응형
'JAVA > JAVA Programming' 카테고리의 다른 글
[JAVA] 문서(txt)파일내 해당단어 중복제거하여 검색하기 (0) | 2014.02.04 |
---|---|
[JAVA] 프로파일링 툴 & APM 툴의 개념 (0) | 2014.02.03 |
[JAVA] Core J2EE 패턴 카탈로그 (0) | 2013.11.24 |
[JAVA] JAR 파일 만들기 (0) | 2013.03.14 |
[JAVA] 숫자에 쉼표(콤마;Comma)넣기, 천(1000) 단위 구분 (0) | 2012.09.07 |