Exam 1Z0-809: Java SE 8 Programmer II

Java SE 8 Programmer II

Question

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(); } Which modification enables the code fragment to print Happy Journey!?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

B.

The code given defines a hierarchy of classes where SolarVehicle extends Vehicle. The Vehicle class defines a method ride() which throws a checked exception FuelNotAvailException. The SolarVehicle class overrides the ride() method and declares that it throws a broader checked exception Exception.

The main method creates an instance of SolarVehicle and calls the ride() method on it. However, since ride() throws a checked exception, it must either be caught or declared to be thrown. In this case, the exception is declared to be thrown in the main method signature.

The goal is to enable the code to print "Happy Journey!" which is done by ensuring that the ride() method of SolarVehicle is executed without throwing an exception.

Option A (public void ride() throws FuelNotAvailException) is incorrect because it does not match the overridden method in Vehicle, which declares that it throws a checked exception of type FuelNotAvailException. It also does not allow for the broader Exception to be thrown.

Option B (protected void ride() throws Exception) is incorrect because it also does not match the overridden method in Vehicle, which declares that it throws a checked exception of type FuelNotAvailException. Although it allows for the broader Exception to be thrown, it is not necessary for the code to work correctly.

Option C (void ride() throws Exception) is incorrect because it changes the signature of the overridden method in SolarVehicle, which does not match the ride() method in Vehicle. Therefore, it does not allow for the super call to ride() to be made, which is required for the code to print "Happy Journey!".

Option D (private void ride() throws FuelNotAvailException) is incorrect because it changes the access level of the method, which is not allowed when overriding a method in a subclass. Additionally, it does not allow for the broader Exception to be thrown.

Therefore, the correct option is B. By changing the SolarVehicle class to:

java
class SolarVehicle extends Vehicle { protected void ride() throws Exception { super.ride(); } }

the code will call the overridden ride() method in SolarVehicle which delegates to the superclass method via super.ride(). Since the superclass method ride() does not throw an exception when it is called, "Happy Journey!" will be printed to the console.