我有以下代码,我想知道为什么我们需要强制转换System.out.println(((Car)y).use());
不管它是否强制转换都像它不需要键入强制转换System.out.println(y.fee());
一样起作用
如果我们删除强制转换Bus z=(Bus)new Toll();
class Toll {
int fee() {
return 1;
}
}
class Car extends Toll {
int fee(){
return 3;
}
int use(){
return 4;
}
}
class Bus extends Toll
{
int fee(){
return 7;
}
}
class Expressway {
public static void main(String[] args) {
Toll y=new Car();
System.out.println(((Car)y).use()); //Line 3 print 4 // why do we need the cast
Bus z=(Bus)new Toll();
System.out.println(z.fee());// LINE 4 ERROR.!!
}
}
答案 0 :(得分:0)
第3行-
System.out.println(((Car)y).use());
不管我们是否投放 还是不像我们不需要键入castSystem.out.println(y.fee());
Toll y=new Car();
System.out.println(y.use());
错误-
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method use() is undefined for the type Toll
以上代码将不起作用,因为您创建了一个对象Toll
,其中不包含方法use()
。编译器不知道您已使用Car()
进行了初始化,因此必须转换为Car()
对象。
System.out.println(((Car)y).use());
第4行-
在这里,您会得到ClassCastException
公共类ClassCastException扩展了RuntimeException
抛出该错误以表明代码已尝试将对象强制转换为 不是实例的子类。
这是因为收费不是公交车。通常,向下浇铸不是优选的想法。