QuestionQ192

Working with Inheritance

Given these requirements:

  • Bus and Boat are Vehicle-type classes.
  • The start() and stop() methods perform common operations across the Vehicle class type.
  • The ride() method performs a unique operation for each type of Vehicle.

Which set of actions satisfies the requirements with optimized code?

  • A
    1. Create an abstract class Vehicle by defining start() and stop() methods, and declaring the ride() abstract method. 2. Create Bus and Boat classes by inheriting the Vehicle class and overriding the ride() method.
  • B
    1. Create an interface Vehicle by defining start() and stop() methods, and declaring the ride() abstract method. 2. Create Bus and Boat classes by implementing the Vehicle class.
  • C
    1. Create an abstract class Vehicle by declaring stop(), start(), and ride() abstract methods. 2. Create Bus and Boat classes by inheriting the Vehicle class and overriding all the methods.
  • D
    1. Create an interface Vehicle by defining default stop(), start(), and ride() methods. 2. Create Bus and Boat classes by implementing the Vehicle interface and overriding the ride() method.
Explanation

An abstract superclass can provide concrete implementations of behavior shared by closely related subclasses, while declaring vehicle-specific behavior as an abstract method. Bus and Boat inherit the single start() and stop() implementations and each must implement its own ride() behavior, avoiding duplication of the common operations. Oracle’s Java documentation recommends abstract classes when closely related classes need to share code and shows subclasses implementing abstract methods.

Learn more

Community Discussion

No comments yet. Be the first to start the discussion!