向下转换是子类引用父类的对象时。我尝试不使用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/