[Java] instanceof를 사용해 어떤 class, subclass, interface인지 구분하기
환경
- Java
사용
instanceof
사용
if (parentObj instanceof ChildClass) {
System.out.println("This is a ChildClass object");
}
예시
Parent Class
- Animal.java
public abstract class Animal {
public abstract void action();
}
Child Classes
- Bird.java
public class Bird extends Animal{
@Override
public void action() {
System.out.println("bird!");
}
}
- Cat.java
public class Cat extends Animal{
@Override
public void action() {
System.out.println("cat!");
}
}
- Dog.java
public class Dog extends Animal{
@Override
public void action() {
System.out.println("dog!");
}
}
Main
- Main.java
public class Main {
public static void main(String[] args) {
Animal bird = new Bird();
Animal cat = new Cat();
Animal dog = new Dog();
testMethod(dog);
testMethod(cat);
testMethod(bird);
}
private static void testMethod(Animal animal) {
if (animal instanceof Bird){
System.out.println("This is bird instance");
} else if (animal instanceof Cat) {
System.out.println("This is cat instance");
} else if (animal instanceof Dog) {
System.out.println("This is dog instance");
} else {
System.out.println("Nothing");
}
animal.action();
}
}
결과
> Task :Main.main()
This is dog instance
dog!
This is cat instance
cat!
This is bird instance
bird!