Java
[instanceof] 나는 어디 소속인가?
고인돌개발자
2021. 5. 12. 21:33
학습목표 : instanceof 의 개념일 이해하고, 예제를 통해 이해할 수 있다.
개념 : 생성된 객체가 어느 클래스에 속해있는지를 확인하는 연산자이다.
특히, Interface 를 통해 객체를 생성할때, 어느 구현체의 것인지 확인 할 때 유용하게 사용 가능하다.
SampleMain.java
package book.oopforsprings.lec04._instanceof;
public class SampleMain {
public static void main(String[] args) {
Bird bird = new Bird();
Bird eagle = new Eagle();
Sparrow sparrow = new Sparrow();
IfFly ifFly = new Eagle();
// Class Type
System.out.printf("1. bird %s \n", bird instanceof Bird);
System.out.println("-----------------");
// Super class , My Class
System.out.printf("2. eagle %s \n", eagle instanceof Bird);
System.out.printf("2. eagle %s \n", eagle instanceof Eagle);
System.out.println("-----------------");
// my Class , Super Class
System.out.printf("3. sparrow %s \n", sparrow instanceof Sparrow);
System.out.printf("3. sparrow %s \n", sparrow instanceof Bird);
System.out.println("-----------------");
// interface Class, my Class , other Class
System.out.printf("4. ifFly %s \n", ifFly instanceof IfFly);
System.out.printf("4. ifFly %s \n", ifFly instanceof Eagle);
System.out.printf("4. ifFly %s \n", ifFly instanceof Sparrow);
System.out.println("-----------------");
// all of Object
System.out.printf("1. bird %s \n", bird instanceof Object);
System.out.printf("2. eagle %s \n", eagle instanceof Object);
System.out.printf("4. sparrow %s \n", sparrow instanceof Object);
System.out.printf("4. ifFly %s \n", ifFly instanceof Object);
}
}
// Super
class Bird{
}
class Sparrow extends Bird implements IfFly{
@Override
public void fly() { }
}
class Eagle extends Bird implements IfFly{
@Override
public void fly() { }
}
// Interface
interface IfFly{
void fly();
}
위 클래스의 구조