用一个例子说明instanceof的用法
时间: 2024-04-29 20:23:13 浏览: 12
假设有一个类Animal,还有两个子类Dog和Cat,现在有一个对象a,我们要判断它是不是Animal类的实例,可以使用instanceof关键字。
```
Animal a = new Dog();
if(a instanceof Animal){
System.out.println("a是Animal类的实例");
}else{
System.out.println("a不是Animal类的实例");
}
```
输出结果为"a是Animal类的实例",因为Dog是Animal的子类,所以Dog的实例也是Animal的实例。如果a是一个String类型的对象,那么输出结果就是"a不是Animal类的实例"。
相关问题
Java instanceof用法,写一个例子
可以的,下面是一个Java instanceof用法的例子:
```java
public class Example {
public static void main(String[] args) {
Object obj = "Hello";
if (obj instanceof String) {
// 如果obj是String类型的,就转换为String类型
String str = (String) obj;
System.out.println(str.toUpperCase());
}
}
}
```
以上代码通过使用instanceof运算符来检查obj是否是一个String对象。如果是,则将obj转换为String类型并将其转换为大写形式打印。如果obj不是String,则忽略它并什么都不做。
Java instanceof用法.写一个例子
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.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)