Answers to Chapter 12 Review Questions

   


Chapter 12

1:

You are writing a Planet class for a solar system simulation program. You need to keep track of the number of instantiated Planet objects. If you were to store this data as a variable inside Planet, should it be an instance variable or a static variable? Why?

A:

As a static variable, because the variable describes the Planet objects as a group.

2:

Can you assign a value to a static variable even if no objects have been created?

A:

Yes.

3:

Can a static variable be accessed from within an object of the class in which it is declared?

A:

Yes.

4:

The following declaration was found inside a class:

 public static const double MassOfElectron = 9.0e-28; 

Is it correct? Why or why not?

A:

No. A const is implicitly static, so it is not valid to also explicitly declare it static.

5:

Does it go against encapsulation principles to declare a const to be public?

A:

No, because the const value cannot be changed.

6:

A class called Planet contains the following declarations:

 class Planet {     private static uint numberOfPlanetsCreated;     private double mass;     ...     public static double CalculateGravity(...)     {         ...     }     public double Density(...)     {         ...     } } 

Is it possible to

  1. Access numberOfPlanetsCreated from within the CalculateGravity method

  2. Access mass from within the CalculateGravity method

  3. Access numberOfPlanetsCreated from within the Density method

  4. Access mass from within the Density method

  5. Access numberOfPlanetsCreated from outside the Planet class by writing Planet.numberOfPlanetsCreated

  6. Access mass from outside the Planet class by writing Planet.mass

A:
  1. Yes.

  2. No.

  3. Yes.

  4. Yes.

  5. Yes.

  6. No.

7:

Among other methods, your class Planet contains two methods of approximately the same length. One is a static method related to the Planet class, the other is an instance method related to a particular Planet object. Suppose 100 objects of type Planet exist inside your running solar system simulation. Is the following statement true or false? "All the instance methods of the Planet class take up approximately 100 times more memory than the static method." Why?

A:

The statement is false because the instance methods share the same code. The static method and the instance methods take up approximately the same memory.

8:

Consider the following method definition:

 public void MyMethod(ref int myValue, int yourValue) {     myValue = 100;     yourValue = 200; } 

Which of the following calls to MyMethod are correct and, if correct, what is the value of myArgument and yourArgument after MyMethod returns (myArgument and yourArgument are both of type int and initially both contain the value 0)?

  1. MyMethod(myArgument, yourArgument)

  2. MyMethod(ref myArgument, ref yourArgument)

  3. MyMethod(ref 10, ref yourArgument)

A:
  1. Invalid. ref must suffix both arguments.

  2. Valid.

  3. Invalid. 10 is not an assignable variable.

9:

Is the following method correct? Why or why not?

 public int Sum(out int x, int y) {     return x + y; } 
A:

Incorrect. Any out parameter must be assigned a value inside its method.

10:

Consider the following method header:

 public double Average(params int[] numbers) 

Which of the following calls to this method are valid? (myArray is an array of base type int with 100 elements.)

  1. Average()

  2. Average(10)

  3. Average(10,20)

  4. Average(10,20,30.0)

  5. Average(myArray)

A:
  1. Valid.

  2. Valid.

  3. Valid.

  4. Invalid, 30.0 is not of type int.

  5. Valid.

11:

The following two method headers were found inside the same class. What can you call the methods?

 public int Sum(int number1, int number2) public double Sum(double number1, double number2) 
A:

Overloaded.

12:
  1. Are the methods with the following method headers correctly overloaded? Why or why not?

     public double Average(int x, int y) public int Average(int x, int y) 
  2. Are the methods with the following method headers correctly overloaded? Why or why not?

     public double Average(int myX, int myY) public int Average(int yourX, int yourY) 
A:
  1. No, only the return type differs (one is double, the other int). However, the return type is not part of a method's signature, so the two method signatures are identical, which is invalid.

  2. No, the parameter names are not part of a method's signature, so even though they differ between the two methods, the two signatures are identical, which is invalid.

13:

A class contains the following method header:

 public uint Sum(uint x, uint y) 

Is the following method call valid? Why or why not? (myByte and yourByte are both of type byte, which is different from Sum's parameter types uint.)

 Sum(myByte, yourByte) 
A:

Yes, the method call is valid. myByte and yourByte are implicitly converted to uints during the method call.

14:

Consider the following class called Planet:

 class Planet {     private double myMass = 2000000;     public double DoSomething(double myMass)     {         return (myMass * this.myMass) + myMass;     } } 

What value will the following method call have when DoSomething returns (if the value of the instance variable myMass is still 2000000)?

 DoSomething(20.0) 
A:

In the line

 return(myMass * this.myMass) + myMass; 

myMass accesses the value of formal parameter myMass (here equal to 20.0), whereas this.myMass accesses the value of the instance variable myMass (here equal to 2000000). So the return value is

 (myMass * this.myMass) + myMass = (20.0 * 2000000) + 20.0 = 40000020 

Answers to Chapter 12 Programming Exercises

1:

Write a class called SportsCar containing the two instance variables maxSpeed and horsepower of type int. Both these instance variables must, in any SportsCar object, hold values that are greater than certain pre-specified values; otherwise, they do not qualify as proper SportsCar objects. In our case, the minimum value for maxSpeed is 200 kilometers/hour, and the minimum value for horsepower is 250 hp. Include suitable member variables in the SportsCar class to hold these values (called maxSpeedRequirement and horsepowerRequirement) and write a method called SportsCheck that returns true if both of the maxSpeed and horsepower for a particular SportsCar object are above the minimum requirements; otherwise, false. Write accessor and mutator methods for maxSpeed, horsepower, maxSpeedRequirement, and horsepowerRequirement.

Include another class containing a Main method to demonstrate the SportsCar class.

Please keep this program available for exercise 2.

2:

Each object instantiated from the SportsCar class you wrote in exercise 1 can only be driven by certain people. Include a method in the SportsCar class that will read in any number of driver names (first names); call it SetLegalDrivers. So, if you have a SportsCar object in your program called sportsCar1, you can set the legal drivers by, for example, the following call:

 sportsCar1.SetLegalDrivers("Tom", "Julie", "Teddy", "Mary") 

or the call

 sportsCar1.SetLegalDrivers("Peter") 

Write a method called DriverCheck that lets you provide a first name as an argument and then returns true if the driver is allowed to drive the SportsCar object; otherwise, it returns false.

Please keep this program handy for exercise 3.

3:

Add a static method called GetMinimumRequirements containing two ref parameters of type int called newMaxSpeed and newHorsepower. This should allow other objects of other classes to call this method and obtain the values of both maxSpeed and horsepower held by the SportsCar class with just one method call. Write a tester class called Calculator with a static method called NumberCruncher that makes a call to GetMinimumRequirements and simply prints out the two values obtained from this call.

Keep the source code intact for the exercise 4.

4:

Equip the SportsCar class with an instance method called MostPowerful that has one formal parameter of type SportsCar called carCompare. Enable the MostPoweful method to compare the SportsCar, referenced by the formal parameter carCompare, with the SportsCar object the MostPowerful method is called for. The most powerful SportsCar object contains the greater horsepower instance variable. Return from the method a reference to the most powerful object.

Allow not only one SportsCar to be passed as an argument to the MostPowerful method, but also two SportsCar objects. In case two arguments of type SportsCar are passed to MostPowerful, three objects are compared and the most powerful SportsCar object returned (hint: use method overloading to implement this functionality).

A:

Answers to all programming exercises are contained in the following program. Program parts relating to particular exercises are marked in the code.

 using System; class SportsCar {     private int maxSpeed = 0;     private int horsepower = 0;     private static int maxSpeedRequirement = 0;     private static int horsepowerRequirement = 0;     private string [] legalDrivers = new string [0]; //Exercise 2     public bool SportsCheck()     {         if((maxSpeed >= maxSpeedRequirement) && (horsepower >= horsepowerRequirement))             return true;         else             return false;     }     public void SetMaxSpeed(int newMaxSpeed)     {         maxSpeed = newMaxSpeed;     }     public int GetMaxSpeed()     {         return maxSpeed;     }     public void SetHorsepower(int newHorsepower)     {         horsepower = newHorsepower;     }     public int GetHorsepower()     {         return horsepower;     }     public static void SetMaxSpeedRequirement(int newMaxSpeedRequirement)     {         maxSpeedRequirement = newMaxSpeedRequirement;     }     public static int GetMaxSpeedRequirement()     {         return maxSpeedRequirement;     }     public static void SetHorsepowerRequirement(int newHorsepowerRequirement)     {         horsepowerRequirement = newHorsepowerRequirement;     }     public static int GetHorsepowerRequirement()     {         return horsepowerRequirement;     }      //Exercise 2     public void SetLegalDrivers(params string [] newLegalDrivers)     {         legalDrivers = newLegalDrivers;     }      //Exercise 2     public bool DriverCheck(string name)     {         foreach(string tempName in legalDrivers)         {             if(tempName == name)                 return true;         }         return false;     }      //Exercise 3     public static void GetMinimumRequirements(ref int newMaxSpeed, ref int newHorsepower)     {         newMaxSpeed = maxSpeedRequirement;         newHorsepower = horsepowerRequirement;     }      //Exercise 4     public SportsCar MostPowerful(SportsCar carCompare)     {         if(carCompare.GetHorsepower() > this.horsepower)             return carCompare;         else             return this;     }      //Exercise 4     public SportsCar MostPowerful(SportsCar carCompare1, SportsCar carCompare2)     {         if(MostPowerful(carCompare1).GetHorsepower() > carCompare2.GetHorsepower())             return MostPowerful(carCompare1);         else             return carCompare2;     } }  //Exercise 3 class Calculator {     public static void NumberCruncher()     {         int sportsCarMaxSpeedReq = 0;         int sportsCarHorsePowerReq = 0;         SportsCar.GetMinimumRequirements(ref sportsCarMaxSpeedReq, ref  graphics/ccc.gifsportsCarHorsePowerReq);         //number crunch...number crunch...number crunch         Console.WriteLine("Value of sportsCarMaxSpeedReq: {0}", sportsCarMaxSpeedReq);         Console.WriteLine("Value of sportsCarHorsePowerReq: {0}", sportsCarHorsePowerReq);     } } class Tester {     public static void Main()     {          //Exercise 1         SportsCar myCar = new SportsCar();         SportsCar yourCar = new SportsCar();          //Calling static methods through class name         SportsCar.SetMaxSpeedRequirement(200);         SportsCar.SetHorsepowerRequirement(250);          //Calling instance methods through object names         myCar.SetMaxSpeed(170);         myCar.SetHorsepower(110);         yourCar.SetMaxSpeed(270);         yourCar.SetHorsepower(300);         Console.WriteLine("It is {0}  that my car is a sports car", myCar.SportsCheck());         Console.WriteLine("It is {0}  that your car is a sports car",  graphics/ccc.gifyourCar.SportsCheck());          //Exercise 2         myCar.SetLegalDrivers("Peter", "Ann", "Eric");         Console.WriteLine("It is {0} that Peter can drive myCar",  graphics/ccc.gifmyCar.DriverCheck("Peter"));         Console.WriteLine("It is {0} that Josephine can drive myCar",  graphics/ccc.gifmyCar.DriverCheck("Josephine"));          //Exercise 3         Calculator.NumberCruncher();          //Exercise 4         SportsCar mostPowerfulCar;         SportsCar herCar = new SportsCar();         herCar.SetMaxSpeed(290);         herCar.SetHorsepower(320);         mostPowerfulCar = myCar.MostPowerful(yourCar);         Console.WriteLine("The most powerful car of your car and my car has {0}  graphics/ccc.gifhorsepowers", mostPowerfulCar.GetHorsepower());         mostPowerfulCar = myCar.MostPowerful(yourCar, herCar);         Console.WriteLine("The most powerful car of your car, my car and her car has {0}  graphics/ccc.gifhorsepowers", mostPowerfulCar.GetHorsepower());     } } 


   


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