A good answer might be:

The complete constructor is seen below.

Complete Constructor

import java.io.* ;

class Car
{
  // instance variables
  int startMiles;   // Stating odometer reading
  int endMiles;     // Ending odometer reading
  double gallons;   // Gallons of gas used 
  // constructor
  Car(  int first, int 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() );
  }
}

Constructors can get complicated; but for most programs all you need to do is copy values from the parameters to the instance variables. You might wonder why you need to do this. Why not just leave the data in the parameters? There are two reasons:

  1. The parameters can be "seen" only by statements inside the body of the constructor (the statements between the two braces.) A method such as calculateMPG() cannot see the parameters of the constructor.
  2. Data in parameters is temporary. Parameters are used to communicate data to the constructor, 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 10:

Now complete the calculateMPG() method.