Picture of Two Objects

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:

Easy. The filled in program is below.

Picture of Two Objects

two car objects

In this program, two defferent Car objects are constructed, each with different data, and the miles per gallon calculation is performed on each.


class Car
{
  . . . .
}

class MilesPerGallon
{
  public static void main( String[] args ) 
  {
    Car car1 = new Car( 32456, 32810, 10.6 );
    System.out.println( "Miles per gallon of car 1 is "  
        + car1.calculateMPG() );

    Car car2 = new Car( 100000, 100300, 10.6 );
    System.out.println( "Miles per gallon of car 2 is " 
        +  car2.calculateMPG() );

  }
}

The picture shows the situation just after the second object has been constructed. Two objects have been constructed according to the definition of Car. The definition of class MilesPerGallon contains the static main() method.

QUESTION 13:

There are two objects, but each uses the same names for its instance variables! Is this a mistake?