007-004-009

Basic Class Aggregation

Medium

Problem Description

Basic Class Aggregation

In this problem, you will define an Engine class and a Car class, implementing aggregation where Car holds an Engine instance as a field.

Learning Objective: Understand aggregation (has-a relationship) where a class field holds an instance of another class

Overview

Implement aggregation where Car class has an Engine class instance as a field.

Specifications

Engine class

  • int horsePower field (package-private)
  • Constructor Engine(int horsePower) to initialize the field

Car class

  • String name field (package-private)
  • Engine engine field (package-private)
  • Constructor Car(String name, Engine engine) to initialize both fields

Example

Engine e = new Engine(200);
Car c = new Car("Sports Car", e);
System.out.println("Car: " + c.name);
System.out.println("Engine: " + c.engine.horsePower + " HP");

Output:

Car: Sports Car
Engine: 200 HP

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