조건문+참조변수 instanceOf 타입(클래스명)
true=> 참조변수가 검사한타입으로 형변환으로 가능하다는 것을 뜻함
참조변수가 참조하고 있는 인스턴스의 실제타입을 체크하여 실제인스턴스와 같은 타입의 참조변수로 형변환을 함
=>인스턴스의 모든 멤버들을 사용 하기위함
void doWord(Car c) {
if (c instanceof FireEngine) {
FireEngine fe=(FireEngine)c;
fe.water();
}else if(c instanceof Ambulance) {
Ambulance a = (Ambulance)c;
a.siren();
}
}
주의 instanceOf 연산결과:자기자신과 조상들(Object포함) 모두 true
=> 검사한 타입으로 형변환해도 아무문제는 없다는뜻
=>자식 객체 먼저 검사 하도록 하자
public class InstanceofTest {
public static void main(String[] args) {
FireEngine fe=new FireEngine();
if(fe instanceof FireEngine) {//자기자신
System.out.println("This is a FireEngine insatance.");
}
if(fe instanceof Car) {//조상
System.out.println("This is a Car instance.");
}
if(fe instanceof Object) {//최고조상인 object로 검사해도 true
System.out.println("This is an Object instance.");
}
System.out.println(fe.getClass().getName());//클래스의 이름 출력
}
}
class Car{}
class FireEngine extends Car{}
'개발 > JAVA' 카테고리의 다른 글
[JAVA]인터페이스 (0) | 2022.08.14 |
---|---|
[JAVA] 추상클래스 (0) | 2022.08.06 |
[JAVA] 다형성 형변환 (0) | 2022.07.12 |
super super() (0) | 2022.07.12 |
오버라이딩 (0) | 2022.07.12 |