Slightly Different 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:

No. Each object has its own identity, so there is no confusion about which variables are which. Each object's constructor gave that object's instance variables the correct values.

Slightly Different Program

If this is confusing, remember that object oriented programming is supposed to imitate the real world. Think of some objects of the real world, say objects of the class Human. Each object has its own identity (ie. Bob is a different individual from Jill) even though each has parts that have the same name. It is not confusing to talk of "Bill's heart" and "Bill's nose," and "Jill's heart" and "Jill's nose." With "dot notation" this would be Bob.heart, Bob.nose, Jill.heart, and Jill.nose.

Below is a slightly different version of the program.


class Car
{
  . . . .
}

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

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

  }
}

QUESTION 14:

How does this program differ from the previous program?