007-004-011

Class Aggregation: Engine and Car

Easy

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 horsePower field (set via constructor)
  • start() method: prints "Engine started: <horsePower> HP"

Car class (Car.java)

  • Engine engine field (received via constructor)
  • String model field (received via constructor)
  • drive() method: calls engine.start() then prints "<model> is driving"

Main class (Main.java)

  • Create an Engine with 200 horsepower
  • Create a Car with model name "Sedan" and the Engine
  • 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