Can't Use Constructor's Parameters in a Method

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 calculateMPG() method can not use the parameters of the constructor.

Can't Use Constructor's Parameters in a Method

In fact, the calculateMPG() method can not even see the parameters of the constructor. Another way of saying this is that the scope of the parameters is limited to the body of the method. The compiler will complain that first, last, and gals are "undefined variables" because they are used outside of their scope. Look back to the complete program to see the correct method.


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  (last - first)/gals  ;       // WRONG, WRONG, WRONG
  }

}

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() );
  }
}

QUESTION 17:

Are you about out of gas?