Complete Constructor

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:

The complete constructor is seen below.

Complete Constructor


class Car
{
  // instance variables
  double startMiles;   // Stating odometer reading
  double endMiles;     // Ending odometer reading
  double gallons;      // Gallons of gas used between the readings

  // constructor
  Car(  double first, double last, double gals  )
  {
    startMiles = first;
    endMiles   = last;
    gallons    = gals;
  }

  // methods
  double calculateMPG()
  {
    return  ;
  }

}

class MilesPerGallon
{
  public static void main( String[] args ) 
  {
    Car car = new Car( 32456, 32810, 10.6 );
    System.out.println( "Miles per gallon is " + car.calculateMPG() );
  }
}

For many programs all that the constructor does is to copy values from its parameters to the instance variables of the new object. You might wonder why you need to do this. Why not just leave the data in the parameters? There are two reasons:

  1. The constructor's parameters can be "seen" only by its own statements. A method such as calculateMPG() cannot see the parameters of the constructor.
  2. Data in parameters is temporary. Parameters are used to communicate data, not to hold data.

Think of a parameter as a scrap of paper containing information handed to the constructor. The constructor has to copy the information to someplace permanent that can be seen by the other methods.

QUESTION 9:

Now complete the calculateMPG() method by filling in the blank.