To improve object-oriented design and comply with the Single Responsibility Principle (SRP), the Vehicle class should be refactored by separating unrelated behaviors into specialized classes and using composition where appropriate. A vehicle should only contain behaviors that are relevant to its type. Instead of placing fly() and sail() methods in a generic Vehicle class, create distinct vehicle types and compose them with reusable components.
Key Points: • Use the IS-A relationship to model specific vehicle types such as Airplane, Boat, and Car, each inheriting only relevant characteristics. • Use the HAS-A relationship (composition) to share common functionality such as Engine, NavigationSystem, or FuelTank across multiple vehicle types. • This design reduces unnecessary methods, improves maintainability, and follows the Single Responsibility Principle.
Example: An Airplane IS-A Vehicle and can fly, while a Boat IS-A Vehicle and can sail. Both vehicles may HAS-A Engine object. This prevents a Boat from having a meaningless fly() method or an Airplane from having an unnecessary sail() method.
Code Example:
class Engine {
public void start() {
System.out.println(
"Engine Started");
}
}
abstract class Vehicle {
protected Engine engine =
new Engine();
}
class Airplane extends Vehicle {
public void fly() {
engine.start();
System.out.println(
"Airplane is flying");
}
}
class Boat extends Vehicle {
public void sail() {
engine.start();
System.out.println(
"Boat is sailing");
}
}
public class Main {
public static void main(String[] args) {
Airplane airplane =
new Airplane();
Boat boat =
new Boat();
airplane.fly();
boat.sail();
}
}Interview Tip: A concise interview answer is: I would remove unrelated methods from the Vehicle class and create specialized subclasses such as Airplane and Boat using the IS-A relationship. Shared functionality such as Engine would be implemented using composition (HAS-A relationship). This follows the Single Responsibility Principle, improves maintainability, and creates a cleaner object-oriented design.