Reputation: 1684
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!
Upvotes: 2
Views: 154
Reputation: 1302
You can fix it with
1.
Sedan c = new Sedan();
c.drive();
2.
or
Car c = new Sedan();
((Sedan) c).drive();
Upvotes: 0
Reputation: 4707
Unfortunately, no, it's not obvious to the compiler.
The compiler is essentially looking at Car c
and the call to drive
. The compiler has no knowledge of the run-time type of the object that c
is pointing to. Because of this, it evaluates the method signature of Car.drive()
, which includes the throws Exception
.
To make it clearer, what if in some other method c
was reassigned to some SUV
object which still throws this exception? The compiler has no way to know the state of the object by the time the drive
method is called.
Upvotes: 5