Class Aggregation: Engine and Car
Problem Description
Class Aggregation: Engine and Car
In this problem: You will create an Engine class with a horsePower field and a start() method, and a Car class that has an Engine field (aggregation relationship). The Car's drive() method calls engine.start() internally, and the results are displayed to standard output.
Learning Objective: Understand class aggregation (one class holding an instance of another class as a field) and learn the delegation pattern between objects
Overview
Aggregation is a "has-a" relationship where one object holds another object. Unlike inheritance (is-a relationship), independent objects cooperate to work together. In this problem, Car holds an Engine and uses the Engine's functionality inside drive().
Specifications
Engine class (Engine.java)
int horsePowerfield (set via constructor)start()method: prints"Engine started: <horsePower> HP"
Car class (Car.java)
Engine enginefield (received via constructor)String modelfield (received via constructor)drive()method: callsengine.start()then prints"<model> is driving"
Main class (Main.java)
- Create an
Enginewith 200 horsepower - Create a
Carwith model name"Sedan"and theEngine - Call
car.drive()
Output Format
Engine started: 200 HP
Sedan is driving
Ready to Try Running Code?
Log in to access the code editor and execute your solutions for this problem.
Don't have an account?
Sign Up