Filling in the Definition

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 data of a Car object should be:

  1. Stating odometer reading,
  2. Ending odometer reading, and
  3. Gallons of gas used between the readings.

The names of the variables are up to the programer.

Filling in the Definition

Here is the program with some of the Car definition filled in:


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

  // constructor


  // methods

}

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

An instance variable is a variable that holds part of the state of an object. Each object (each "instance" of the class) contains its own instance variables. Instance variables hold on to their values as long as the object exists. An assignment statements can change the value in an instance variable (see the next chapter), but otherwise it holds its value for the lifetime of the object.

QUESTION 6:

What must the constructor of Car be named?