Adding a fillUp() 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:

No. As is currently stands, the instance variables of all objects cannot be accessed from outside the objects, and there are no access methods to change them.

Adding a fillUp() Method

It would be nice to make the program more useful by writing a method for Car that acts like a visit to the filling station. The new method does this:

  • void fillUp( int newOdo, double fillUpGals )
    • Change the state of a Car by using the odometer reading and the number of gallons of the most recent fillup.

The state of a Car object changes when its instance variables are changed. The number of gallons of the new fillup will replace the old value, and the odometer readings will have to be adjusted. Here is class Car with some more blanks:

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

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

  // methods
  double calculateMPG()
  {
    return (endMiles - startMiles)/gallons ;
  }

  void fillUp(int newOdo, double fillUpGals )
  {

     =  ;

     =  ;

     =  ;

  }
}

QUESTION 12:

Fill in the blanks for the new method. This may take a little bit of thought.

Click here for a