Here's a basic example demonstrating the usage of the "instanceof" operator.
class Animal {
// animal class definition
}
class Dog extends Animal {
// dog class definition
}
class Cat extends Animal {
// cat class definition
}
public class Main {
public static void main(String[] args) {
Animal animal1 = new Dog(); // create a Dog object and assign it to an Animal reference
Animal animal2 = new Cat(); // create a Cat object and assign it to an Animal reference
// test if animal1 is an instance of Dog
if (animal1 instanceof Dog) {
System.out.println("animal1 is a Dog");
} else {
System.out.println("animal1 is not a Dog");
}
// test if animal2 is an instance of Dog
if (animal2 instanceof Dog) {
System.out.println("animal2 is a Dog");
} else {
System.out.println("animal2 is not a Dog");
}
// test if animal1 is an instance of Animal
if (animal1 instanceof Animal) {
System.out.println("animal1 is an Animal");
} else {
System.out.println("animal1 is not an Animal");
}
// test if animal1 is an instance of Cat
if (animal1 instanceof Cat) {
System.out.println("animal1 is a Cat");
} else {
System.out.println("animal1 is not a Cat");
}
}
}
Output:
animal1 is a Dog
animal2 is not a Dog
animal1 is an Animal
animal1 is not a Cat
In this example:
- We have a class hierarchy with "Animal" as the superclass and "Dog" and "Cat" as subclasses.
- We create instances of "Dog" and "Cat" and assign them to variables of type "Animal".
- We use the "instanceof" operator to test whether each object is an instance of a specific class ("Dog", "Cat") or interface ("Animal").
- Based on the results of the "instanceof" checks, we print appropriate messages indicating the type of each object.
Nenhum comentário:
Postar um comentário