Java SE 8 Programmer II — Question 19
Given:
class FuelNotAvailException extends Exception { }
class Vehicle {
void ride() throws FuelNotAvailException { //line n1
System.out.println("Happy Journey!");
}
}
class SolarVehicle extends Vehicle {
public void ride () throws Exception { //line n2
super ride ();
}
}
and the code fragment:
public static void main (String[] args) throws FuelNotAvailException, Exception {
Vehicle v = new SolarVehicle ();
v.ride();
}
Happy Journey!?
Which modification enables the code fragment to print
line n1 with public void ride() throws FuelNotAvailException {
Answer options
- A. Replace line n1 with protected void ride() throws Exception {
- B. Replace line n2 with void ride() throws Exception {
- C. Replace line n2 with private void ride() throws FuelNotAvailException {
- D. Replace
Correct answer:
Explanation
The correct answer is C, as changing line n2 to private void ride() throws FuelNotAvailException allows the overridden method in SolarVehicle to throw the same exception type that the parent method declares, thus maintaining the exception hierarchy. Options A and B do not correctly match the exception types required by the parent method, and option D is incomplete.