The following code doesn't compile because of an unhandled exception, though it seems to me like there should be no problem:
class Car {
public void drive() throws Exception {
System.out.println("Driving...");
}
}
public class Sedan extends Car {
public void drive() {
System.out.println("Driving Sedan...");
}
public static void main(String[] args) {
Car c = new Sedan();
c.drive(); //unhandled exception!
}
}
Shouldn't it be obvious to the compiler that when the overriding method c.drive()
is called, a checked exception will not be thrown? Why is it that just because the reference is of type Car instead of type Sedan, we have to treat drive as if it still throws a checked exception? The overriding method doesn't!