You want to design a Java program where different vehicle types must provide their own startEngine() behavior. Which approach using abstract methods is best to ensure this?
hard📝 Application Q15 of 15
Java - Abstraction
You want to design a Java program where different vehicle types must provide their own startEngine() behavior. Which approach using abstract methods is best to ensure this?
ACreate an abstract class Vehicle with an abstract method startEngine(), then subclass it for each vehicle type implementing startEngine().
BCreate a concrete class Vehicle with a startEngine() method that prints a generic message, and override it in subclasses.
CCreate an interface Vehicle with a default startEngine() method, and override it in subclasses if needed.
DCreate a class Vehicle with a private startEngine() method and call it from subclasses.
Step-by-Step Solution
Solution:
Step 1: Understand requirement for mandatory implementation
The program requires each vehicle type to provide its own startEngine() behavior, so subclasses must be forced to implement this method.
Step 2: Evaluate options for enforcing implementation
Create an abstract class Vehicle with an abstract method startEngine(), then subclass it for each vehicle type implementing startEngine(). uses an abstract class with an abstract method, forcing subclasses to implement startEngine(). Create a concrete class Vehicle with a startEngine() method that prints a generic message, and override it in subclasses. provides a generic method that can be overridden but does not force implementation. Create an interface Vehicle with a default startEngine() method, and override it in subclasses if needed. uses an interface with a default method, which subclasses may skip overriding. Create a class Vehicle with a private startEngine() method and call it from subclasses. uses a private method, which is not accessible to subclasses.
Final Answer:
Create an abstract class Vehicle with an abstract method startEngine(), then subclass it for each vehicle type implementing startEngine(). -> Option A