Answers to Chapter 14 Review Questions

   


Chapter 14

1:

  1. If Speed is a property defined inside an object called myRocket, what is the general name for the block of statements defined for the Speed property that are executed when the following line is executed?

     myRocket.Speed = 40; 
  2. When the following line is executed?

     travelTime = distance / myRocket.Speed; 

A:
  1. set statement block or set accessor

  2. get statement block or get accessor

2:

Which capitalization style is recommended for

  1. Instance variables?

  2. Methods?

  3. Properties?

A:
  1. Camel casing

  2. Pascal casing

  3. Pascal casing

3:

The following lines specify an instance variable declaration and what is meant to be a property with the task of allowing access to the instance variable speed from outside the object. However, the property definition has four problems that need to be fixed before it will work correctly. Find and fix the problems.

  private double speed; public double Speed {     get     {         return speed;     } } 
A:

Change private to public, change int to double, remove the parentheses after Speed, and return speed not Speed.

  private double speed; public double Speed {     get     {         return speed;     } } 
4:

What is delayed initialization? When would you use it? Could delayed initialization also be implemented with accessor and mutator methods?

A:

Delayed initialization When a program does not initialize an instance variable until its associated get statement block is called the first time. Delayed initialization is used with instance variables that are resource demanding to update and rarely used.

Delayed initialization can also be implemented with accessor and mutator methods.

5:

The header of the following indexer declaration has three problems. What are they?

 static int myIndexer this [ ] {     ... } 
A:

An indexer cannot be static and does not have a name (as myIndexer); only the keyword this is used. At least one parameter must be specified inside the square brackets. The following is a valid indexer header:

 public int this [int index] {     ... } 
6:

The Rainfall class contains an array with twelve elements. It also contains an indexer to access the array elements, which, like its array, is zero-based (first element is zero). A rainfallParis object is instantiated from the Rainfall class.

  1. Write a statement that assigns the value of the third element of rainfallParis to the variable rainfallMarch.

  2. Write a statement that assigns the value rainfallJuly to the seventh element of rainfallParis.

  3. You are extending the Rainfall class with another method. Among other things in this method, you need to assign the third element of the indexer to your myMarchRainfall variable. Write the statement.

A:
  1. rainfallMarch = rainfallParis[2];

  2. rainfallParis[6] = rainfallParis;

  3. myMarchRainfall = this[2];

7:

You have just finished implementing your Car class and are satisfied with the end result. During a quiet moment of contentment, your colleague suddenly suggests that to make the Car class perfect, you should include operator overloading for the class so it can be used with the + and - operators and support code like car3 = car1 + car2. Is this a good idea? Why or why not?

A:

This is not a good idea. We don't know intuitively how the Car objects are being added together, so including operator overloading for the Car class is likely to make the code more cryptic.

8:

Why is operator overloading sometimes referred to as syntactic sugar?

A:

Operator overloading changes the code's appearance syntactically (sometimes it looks sweeter), but underneath the syntax surface, operator overloading is just another way of calling a method.

9:

Recall the TimeSpan class from Listing 14.7. It already includes an operator + method to add two TimeSpan objects together and assign the result to a TimeSpan reference variable. Your colleague decides to include an operator - method so that TimeSpan objects can be subtracted. The following is the code he initially inserted into the TimeSpan class. It contains several flaws. Find them.

 private TimeSpan   (TimeSpan timeSpan1, TimeSpan timeSpan2) {     return (timeSpan1.Seconds   timeSpan2.Seconds) } 
A:

The operator - method must be public and static and include the operator keyword in front of the minus symbol. Furthermore, it must return a TimeSpan object not a value of type uint.

The correct operator - method looks as follows:

 public static TimeSpan operator- (TimeSpan timeSpan1, TimeSpan timeSpan2) {     TimeSpan differenceTimeSpan = new TimeSpan();     differenceTimeSpan.Seconds = timeSpan1.Seconds - timeSpan2.Seconds;     return differenceTimeSpan; } 
10:

Among other program elements, your program contains the two classes EarthTimeSpan and BliposTimeSpan. Each class still contains an instance variable called totalSeconds of type uint. In this case, EarthTimeSpan contains a user-defined explicit conversion to the type short, and BliposTimeSpan contains a user-defined implicit conversion from the type decimal to BliposTimeSpan. myShort is a variable of type short and myDecimal is a variable of type decimal, earthTimeSpan1 is of type EarthTimeSpan and bliposTimeSpan1 is of type BliposTimeSpan. Determine whether each of the following statements is valid:

  1. myDecimal = bliposTimeSpan1;

  2. myDecimal = (decimal) bliposTimeSpan1;

  3. myShort = (short) bliposTimeSpan1;

  4. myShort = earthTimeSpan1;

  5. myShort = (short)earthTimeSpan;

  6. myDecimal = earthTimeSpan;

  7. myDecimal = (decimal)earthTimeSpan;

  8. bliposTimeSpan1 = earthTimeSpan1;

  9. bliposTimeSpan1 = (short)earthTimeSpan1;

  10. bliposTimeSpan1 = (decimal)earthTimeSpan1;

  11. earthTimeSpan1 = bliposTimeSpan1;

  12. earthTimeSpan1 = (short)bliposTimeSpan1;

  13. earthTimeSpan1 = (decimal)bliposTimeSpan1;

A:
  1. Invalid

  2. Invalid

  3. Invalid

  4. Invalid

  5. Valid

  6. Invalid

  7. Valid

  8. Invalid

  9. Valid

  10. Valid

  11. Invalid

  12. Invalid

  13. Invalid

11:

You are writing a program that will assist architects in drawing architectural plans. The program contains many classes that rely on manipulating two-dimensional drawings. One of these classes is called Bathroom, and it represents and manipulates drawings of bathrooms. It needs a class called Point to represent a point consisting of two coordinates. Would it be a good idea to nest this class in the Bathroom class? Why or why not?

A:

If there is a class called Bathroom, there are also likely to be classes with names such as Kitchen, Bedroom, and so on. All these classes have a fundamental need to manipulate two-dimensional drawings and therefore a need to use the Point class. Consequently, it is not a good idea to isolate the Point class inside Bathroom. Instead, it should be positioned where all these classes can access it and share the functionality provided by the Point class.

Answers to Chapter 14 Programming Exercises

1:

Expand the Bicycle class of Listing 14.2 to contain an instance variable called age that represents the age of a Bicycle. Write a property that allows users of the Bicycle class to set and get the age instance variable. Include code that prevents the age instance variable from being assigned a negative value or a value greater than 200. Equip the Bicycle class with an instance variable called numberOfAgeAccesses to represent the number of times the age instance variable has been accessed. Include a property to access numberOfAgeAccesses. Should this latter property contain both a set and a get statement block?

A:

The following code could be inserted into the Bicycle class to answer Exercise 1. Note: This code does not compile separately.

 const byte MaxAge = 200; private byte age; private uint numberOfAgeAccesses = 0; public byte Age {     get     {         numberOfAgeAccesses++;         return age;     }     set     {         if (value > MaxAge)             Console.WriteLine("Error. {0} exceeds the age limit {1}", value, MaxAge);         else if (value < 0)             Console.WriteLine("Error. {0} cannot be less than 0", value);         else             age = value;     } } public uint NumberOfAgeAccesses {     get     {         return numberOfAgeAccesses;     } } 
2:

Write a class called Rainfall containing a one-dimensional array with 12 elements representing monthly rainfall measurements. Include the following features:

  • Allow the users of the Rainfall objects to access the 12 array elements with an index of type int as if these objects themselves were arrays. Let the first month be identified with index 1 (not zero). Make the program check that all indexes provided are within the correct bounds. Have the program count the number of times a rainfall reading has been accessed. Store this number in an instance variable called numberOfRainAccesses.

  • Include a property called Average that calculates the average monthly rainfall.

  • Please keep this class for use in exercise three.

3:

Allow two Rainfall objects to be added together with the + symbol. This should allow you to write the following:

 totalRainfall = rainfallA + rainfallB; 

where all three objects are of type Rainfall. totalRainfall should now hold an array where the first element holds the result of adding the first element of the array in rainfallA together with the first element of the array in rainfallB; the second element holds the result of adding the second element of the array in rainfallA together with the second element of the array in rainfallB, and so on.

Allow two Rainfall objects to be compared with the < and > comparison operators. Let the average of the 12 elements in each of the two compared objects be the deciding factor. So, if rainfallA's average rainfall is greater than that of rainfallB, the following expression will be true:

 rainfallA > rainfallB 

and the next expression will be false:

 rainfallA < rainfallB 

Use the Average property that you have already written in exercise 2 to provide the necessary information for the comparison.

Please save the code for use in exercise 4.

4:

Write a class called RainfallQuarterly containing an array with four elements to store rainfall information on a quarterly basis. Write user-defined conversions between RainfallQuarterly and Rainfall going in both directions. A Rainfall object is converted to a RainfallQuartely object by adding together the first four array elements and assigning that value to the first array element of the RainfallQuarterly object, and so on. A RainfallQuartely object is converted to a Rainfall object by dividing the first array element by four and assigning this value to each of the first four elements in the Rainfall array, and so on. Should both conversions be explicit or just one of them, or perhaps both of them should be implicit? Why? Hint: In which conversion is data lost? In which conversion is it not lost?

A:

The following code could be an answer to Exercises 2 4. Note: This code does not compile independently.

 // This class is an answer to questions 2 and 3. class Rainfall {     private uint[] rainfall = new uint[12];     private uint numberOfRainAccesses = 0;      //Initialize the rainfall array     public Rainfall()     {         for(int i = 0; i < 12; i++)         {             rainfall[i] = 0;         }     }     public uint this [int index]     {         get         {             if (index < 1 || index > 12)             {                 Console.WriteLine("Index is out of bounds");                 return 0;             }             else             {                 numberOfRainAccesses++;                 return rainfall[index - 1];             }         }         set         {             if (index < 1 || index > 12)                 Console.WriteLine("Index is out of bounds");             else                 rainfall[index - 1] = value;         }     }     public uint NumberOfRainAccesses     {         get         {             return numberOfRainAccesses;         }     }     public uint Average     {         get         {             uint sum = 0;             for (int i = 0; i < 12; i++)             {                 sum += rainfall[i];             }             return (sum / 12);         }     }     public static Rainfall operator+ (Rainfall rainfall1, Rainfall rainfall2)     {         Rainfall sumRainfall = new Rainfall();          //Add each corresponding month pair of the two          //Rainfall objects together and assign the result          //to the corresponding month of sumRainfall.         for (int i = 1; i < 13; i++)         {             sumRainfall[i] = rainfall1[i] + rainfall2[i];         }         return sumRainfall;     }     public static bool operator> (Rainfall rainfall1, Rainfall rainfall2)     {         if (rainfall1.Average > rainfall2.Average)             return true;         else             return false;     }     public static bool operator< (Rainfall rainfall1, Rainfall rainfall2)     {         if (rainfall1.Average < rainfall2.Average)             return true;         else             return false;     } }  //This class is written as an answer to programming exercise 4. class RainfallQuarterly {     private uint[] rainQuarterly = new uint[4];     public uint this [int index]     {         get         {             if (index < 1 || index > 4)             {                 Console.WriteLine("Index is out of bounds");                 return 0;             }             else             {                 return rainQuarterly[index - 1];             }         }         set         {             if (index < 1 || index > 4)                 Console.WriteLine("Index is out of bounds");             else                 rainQuarterly[index - 1] = value;         }     }      //Implicit because no data is lost: For each quarter the three corresponding      //months are added together and the sum assigned to this quarter.     public static implicit operator RainfallQuarterly (Rainfall convertFrom)     {         RainfallQuarterly newRainQuarterly = new RainfallQuarterly();         uint tempSum;         int tempIndex = 1;          //For each quarter add the corresponding months together and          //add this value to the quarter         for (int i = 1; i < 5; i++)         {             tempSum = 0;             for (int j = 1; j < 4; j++)             {                 tempSum += convertFrom[tempIndex];                 tempIndex++;             }             newRainQuarterly[i] = tempSum;         }         return newRainQuarterly;     }      //Explicit because data is lost when each quarterly amount is turned into      //three monthly values all of the same size.     public static explicit operator Rainfall (RainfallQuarterly convertFrom)     {         Rainfall newRainMonthly = new Rainfall();         int tempIndex = 1;         uint tempAverage;          //For each quarter calculate a monthly average rainfall          //Assign this value to the months of this quarter         for (int i = 1; i < 5; i++)         {             tempAverage = convertFrom[i] / 3;             for (int j = 1; j < 4; j++)             {                 newRainMonthly[tempIndex] = tempAverage;                 tempIndex++;             }         }         return newRainMonthly;     } } 


   


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net