[Java](EN) Use instanceof operator to determine which particular class, subclass, interface is
Environment and Prerequisite
- Java
Usage
- Use
instanceof
if (parentObj instanceof ChildClass) {
System.out.println("This is a ChildClass object");
}
Example
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();
}
}
Result
> Task :Main.main()
This is dog instance
dog!
This is cat instance
cat!
This is bird instance
bird!