Java(폐지)/Java 공부
instanceof 연산자
kyeongjun-dev
2020. 7. 20. 14:46
instanceof 연산자
인스턴스는 '클래스를 통해 만들어진 객체'이다. instanceof 연산자는 만들어진 객체가 특정 클래스의 인스턴스인지 물어보는 연산자다. instanceof 연산자는 결과로 true 또는 false를 반납한다.
- 사용법
객체_참조_변수 instanceof 클래스명
예제1
package instanceofOf01;
class 동물 {
}
class 조류 extends 동물 {
}
class 펭귄 extends 조류 {
}
public class Driver {
public static void main(String[] args) {
동물 동물객체 = new 동물();
조류 조류객체 = new 조류();
펭귄 펭귄객체 = new 펭귄();
System.out.println(동물객체 instanceof 동물);
System.out.println(조류객체 instanceof 동물);
System.out.println(조류객체 instanceof 조류);
System.out.println(펭귄객체 instanceof 동물);
System.out.println(펭귄객체 instanceof 조류);
System.out.println(펭귄객체 instanceof 펭귄);
System.out.println(펭귄객체 instanceof Object);
}
}
- 결과 : 전부 true 출력
true
true
true
true
true
true
true
예제2
package instanceofOf01;
class 동물 {
}
class 조류 extends 동물 {
}
class 펭귄 extends 조류 {
}
public class Driver {
public static void main(String[] args) {
동물 동물객체 = new 동물();
동물 조류객체 = new 조류();
동물 펭귄객체 = new 펭귄();
System.out.println(동물객체 instanceof 동물);
System.out.println(조류객체 instanceof 동물);
System.out.println(조류객체 instanceof 조류);
System.out.println(펭귄객체 instanceof 동물);
System.out.println(펭귄객체 instanceof 조류);
System.out.println(펭귄객체 instanceof 펭귄);
System.out.println(펭귄객체 instanceof Object);
}
}
- 결과 : 모두 true이다.
객체 참조 변수의 타입이 아닌 실제 객체의 타입에 의해 처리하기 때문에 모두 true가 출력된다.
예제3
- instanceof 연산자는 클래스들의 상속 관계뿐만 아니라 인터페이스의 구현 관계에서도 동일하게 적용된다.
package instanceOf03;
interface 날수있는 {
}
class 박쥐 implements 날수있는{
}
class 참새 implements 날수있는{
}
public class Driver {
public static void main(String[] args) {
날수있는 박쥐객체 = new 박쥐();
날수있는 참새객체 = new 참새();
System.out.println(박쥐객체 instanceof 날수있는);
System.out.println(박쥐객체 instanceof 박쥐);
System.out.println(참새객체 instanceof 날수있는);
System.out.println(참새객체 instanceof 참새);
}
}
- 모두 true를 출력한다.