所以我想弄清楚为什么一个程序正在编译它的方式,希望你们能为我解释它.
class Vehicle{
public void drive() throws Exception{
System.out.println("Vehicle running");
}
}
class Car extends Vehicle{
public void drive(){
System.out.println("Car Running");
}
public static void main(String[] args){
Vehicle v = new Car();
Car c = new Car();
Vehicle c2 = (Vehicle) v;
c.drive();
try {
v.drive();
} catch (Exception e) {
e.printStackTrace();
} //try v.drive()
try {
c2.drive();
} catch (Exception e) {
e.printStackTrace();
} //try c2.drive()
}
}
Run Code Online (Sandbox Code Playgroud)
所以上述程序的输出将会是
汽车
跑车
跑车运行
我的问题是,为什么我必须执行try/catch块来为v和c2对象调用drive()方法而不是c?他们都是Car的例子,所以这里发生了什么?