gpt4 book ai didi

java - 使用 instanceof 运算符向下转型

转载 作者:行者123 更新时间:2023-11-29 03:00:48 25 4
gpt4 key购买 nike

向下转型是子类引用父类的对象。我尝试在没有 instanceof 运算符的情况下这样做。

class Food { }  
class bread4 extends Food {
static void method(Food a) {
bread4 b=(bread4)a;
System.out.println("ok downcasting performed");
}
public static void main (String [] args) {
Food a=new bread4();
bread4.method(a);
}
}

任何人都可以使用 instanceof 运算符帮助我吗?

最佳答案

instanceof 运算符提供运行时类型检查。例如,如果您有一个类 Food 和两个子类型 Bread4 和 Bread5,那么:

static void method(Food a) {
Bread4 b = (Bread4) a;
System.out.println("Downcasting performed");
}

像这样调用这个方法:

Food four = new Bread4();
Food five = new Bread5();
Bread4.method(four); //the cast inside is done to Bread4, therefore this would work
Bread4.method(five); //the object of type Bread5 will be cast to Bread4 -> ClassCastException

为避免这种情况,您可以使用instanceof 运算符

static void method(Food a) {
if (a instanceof Bread4) {
Bread4 b = (Bread4) a;
System.out.println("Downcasting performed");
}
}

因此,万一你打电话

Bread4.method(five)

检查返回 false,因此没有发生 ClassCastException。

希望这能回答您的问题。

关于java - 使用 instanceof 运算符向下转型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35099748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com