Java instanceof用法.写一个例子
时间: 2024-05-10 16:19:47 浏览: 47
Sure, here's an example:
```
public class Animal {
public void eat() {
System.out.println("This animal is eating.");
}
}
public class Dog extends Animal {
public void bark() {
System.out.println("Woof woof!");
}
}
public class InstanceOfExample {
public static void main(String[] args) {
Animal animal = new Dog();
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
dog.bark();
} else {
animal.eat();
}
}
}
```
In this example, we have an `Animal` class and a `Dog` class that extends `Animal`. We create a new instance of `Dog` and assign it to an `Animal` reference variable. We then use `instanceof` to check if the `Animal` object is also a `Dog`. If it is, we can safely cast it to a `Dog` and call `bark()`. If it's not a `Dog`, we can call the `eat()` method on the `Animal` object.
阅读全文