Java instanceof用法,写一个例子
时间: 2024-05-07 08:23:54 浏览: 15
可以的,下面是一个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.
Java instanceof()方法 找两个非常简单的例子
例子1:判断对象是否为某个类的实例
```java
String str = "Hello World";
if (str instanceof String) {
System.out.println("str is an instance of String");
}
```
输出结果为:
```
str is an instance of String
```
例子2:判断对象是否为某个基本数据类型的实例
```java
int num = 10;
if (num instanceof Integer) {
System.out.println("num is an instance of Integer");
}
```
这段代码会编译失败,因为基本数据类型不能使用 instanceof 进行判断。
相关推荐
![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)