Java的instanceof判断类型的用法
时间: 2023-07-29 16:13:27 浏览: 45
在 Java 中,instanceof 是一个运算符,用于检查一个对象是否是一个特定类的实例或者是其子类的实例。
instanceof 运算符的语法如下:
```
object instanceof class
```
其中,object 是要进行类型判断的对象,class 是要判断的类型。
如果 object 是 class 类型或者其子类的类型,则返回 true,否则返回 false。
下面是一个使用 instanceof 运算符的例子:
```java
public class Animal {
// ...
}
public class Dog extends Animal {
// ...
}
public class Cat extends Animal {
// ...
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
if (animal instanceof Dog) {
System.out.println("animal is a dog");
} else if (animal instanceof Cat) {
System.out.println("animal is a cat");
} else {
System.out.println("animal is neither a dog nor a cat");
}
}
}
```
在这个例子中,我们定义了一个 Animal 类和两个继承自 Animal 的子类 Dog 和 Cat。在 Main 类中,我们创建了一个 Animal 类型的对象 animal,但是它实际上是一个 Dog 类型的对象。
在运行时,程序会使用 instanceof 运算符来检查 animal 是否是一个 Dog 类型的对象。由于 animal 是 Dog 类型的对象,所以程序会输出 "animal is a dog"。