Constructors used inside a Constructor

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:

See below.

Constructors used inside a Constructor

The constructor for Fleet is given (in its parameters) all the information it needs to build two cars. It uses the Car constructor for this (twice). The Car object references are kept safe in the instance variables of the Fleet objects.

class Fleet
{
  // data
  Car town;
  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


}

class FleetTester
{
  public static void main ( String[] args)
  {
    Fleet myCars = new Fleet( 1000, 1234, 10, 777, 999, 20 );
  }
}

Usually you would say that myCars is a Fleet that contains two Car objects. But be careful: the class definition of Fleet does not contain the definition of Car. And at run time, the memory that makes up a Fleet object does not contain the memory that makes up its two Car objects.

QUESTION 7:

If a Fleet object is constructed, how many new objects are there?