Specifications for the Car class

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

You would expect to use:

  1. Starting odometer reading,
  2. Ending odometer reading, and
  3. Gallons of gas used between the readings.

Specifications for the Car class

Think about the classes you need before you start writing. This makes programming easier and your programs will have fewer bugs. Object oriented design means deciding what classes you need, what data the objects hold, and how the objects will behave. Let us do that with the Car class.


Car

A class that calculates miles per gallon.

Variables

  • double startMiles; // Starting odometer reading
  • double endMiles; // Ending odometer reading
  • double gallons; // Gallons of gas used between the readings

Constructors

  • Car( double startOdo, double endingOdo, double gallons )
    Creates a new instance of a Car object with the starting and ending odometer readings and the number of gallons of gas consumed.

Methods

  • double calculateMPG()
    calculates and returns the miles per gallon for the car.

Look at the parameter list for the constructor:

Car( double startOdo, double endingOdo, double gallons );

This says that the constructor must be called with three items of data: three double precision values.

QUESTION 2:

Could a main() method create a Car object?