Better Encapsulated Program

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 improved version of the program is below. It will run just fine.

Better Encapsulated Program

Logically the program is the same as before, but with the instance variables made private there is a greater enforcement of encapsulation.

class Fleet
{
  // data
  private Car town;
  private Car suv;

  // constructor
  Fleet( int start1, int end1, double gal1, 
         int start2, int end2, double gal2 )
  {
    town = new Car( start1, end1, gal1) ;
    suv  = new Car( start2, end2, gal2) ;
  }

  // method
  double calculateMPG()
  {
    double sumMPG; 

    sumMPG = town.calculateMPG() + suv.calculateMPG() ;

    return sumMPG/2.0;
  }
}

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

}

class FleetTester
{
  public static void main ( String[] args)
  {
    Fleet myCars = new Fleet( 1000, 1234, 10, 777, 999, 20 );
    System.out.println("Fleet average MPG= " + myCars.calculateMPG() );
  }
}

QUESTION 11:

Is it possible (in the new version of the program) for the values of the odometer readings of the cars to change?