Answers to Chapter 17 Review Questions

   


Chapter 17

1:

Consider an Animal class from which the Dog, Cat, and Duck classes are derived. Suppose that any Animal can make a sound. Where would you locate the Sound method? Would you provide an implementation for this method or declare it abstract? Why?

A:

The Sound method should be positioned in the Animal class because any animal can make a sound. We don't know the sound an Animal makes (it could be meow, vrooff, or something else), so Sound should be declared abstract in Animal.

2:

If the Sound method of the Animal class was declared abstract, would you be able to instantiate an object from this class? Why or why not?

A:

No. The Animal class must be declared abstract because it contains the abstract Sound method. An abstract class cannot be instantiated, because otherwise it would be possible to call methods without any implementation.

3:

You want to implement a Sound method in each of Animal's three subclasses and call these three methods polymorphically. Which keywords would you use to declare the Sound method in Animal and in the three subclasses to allow this scenario to take place? Write the method headers in the Animal class and the three subclasses.

A:

Method header of Sound in the Animal class is as follows:

 public abstract void Sound(); 

Sound's header is the same in all three derived classes:

 public override void Sound() 
4:

What's wrong with the following piece of code?

 public abstract void Sound() {     Console.WriteLine("Quaaakkk quaaakkk"); } 
A:

An abstract method cannot have an implementation.

5:

If you want to call the Sound method of the three different subclasses polymorphically, would you need to do this for a variable of type Animal or for three variables of the types Cat, Dog, and Duck?

A:

For a variable of type Animal.

6:

Suppose the Sound method has been declared in the Animal class and implemented in the three subclasses so each of these three subclass implementations can be called through dynamic binding. Which of the three implementations are called in the second line of the following code:

 Animal myAnimal = new Dog(); myAnimal.Sound; 
A:

The implementation of the Sound method written in the Dog class is called and executed.

7:

You have another animal class called Lion also containing a Sound method that you want to call polymorphically through a variable of type Animal. What do you need to do for this to be possible?

A:

Let the Lion class be derived from the Animal class. Make sure the Sound method is defined with the override keyword.

8:

You need to find out if the variable myAnimal (declared as Animal myAnimal;) is referencing an object of type Dog. How can you find out?

A:

By using the is operator as follows:

 (myAnimal is Dog) 

which returns true if myAnimal is referencing an object of type Dog.

9:

You need to cast myAnimal into an object of type Cat, but only if myAnimal does contain a Cat. Show two different ways to do this.

A:

You can use the is operator as shown in the following lines:

 if (myAnimal is Cat)     myCat = (Cat) myAnimal 

or the as operator as in the following line:

 myCat = myAnimal as Cat; 
10:

Consider the Cat class from the previous questions. You have only defined the Sound method for it. Another programmer is using your Cat class and writes the following calls in his code (lines 2 and 3):

 Cat myCat = new Cat(); myCat.Jump(); Console.WriteLine(myCat.ToString()); 

Are both these calls valid? If any of them are valid, what is the outcome of the call? Explain what is going on here.

A:

myCat.Jump() is not valid because Cat does not contain any Jump method.

However, myCat.ToString() is valid because Cat implicitly inherits the ToString method from the System.Object class. The call returns the name of the class in a string ("Cat").

11:

If most methods are likely to be declared virtual, why is a method not virtual by default?

A:

The virtual methods of a base class can create more havoc in derived classes than non-virtual methods. virtual methods are executed slightly slower than non-virtual methods.

12:

Why doesn't C# support multiple inheritance?

A:

Several subtle problems are associated with multiple inheritance.

13:

What's the problem with the following interface definition:

 interface IRecoverable {     public void Recover()     {         Console.WriteLine("I am recovering");     } } 
A:

First, the access modifier public cannot be applied to the method Recover. Second, Recover is implicitly abstract, so it cannot have an implementation. A semicolon must be inserted instead of the implementation.

14:

A programmer suggests that you can improve your code by exchanging the Animal class introduced in questions 1 3 with an interface called IArticulateable. Is he or she right? Why or why not?

A:

You can create the same functionality with IArticulateable, but you cannot improve the code. The power of interfaces is realized when you want to implement polymorphism on a group of classes that do not have a common ancestor (Animal is a common ancestor).

Answers to Chapter 17 Programming Exercises

1:

Write a simple Account class containing an instance variable called balance and a property called Balance to provide access to balance. Allow the Account class to be sorted by the generic BubbleSortAscending contained in the Sorter class of Listing 17.13 by letting it implement the IComparable interface. Test your Account class by creating an array of Accounts with different balances and pass this as an argument to the BubbleSortAscending method.

A:

Exercise 1:

 using System; public interface IComparable {     int CompareTo(IComparable comp); } public class Account : IComparable {     private decimal balance;     public Account(decimal initBalance)     {         balance = initBalance;     }     public decimal Balance     {         get         {             return balance;         }         set         {             balance = value;         }     }     public virtual int CompareTo(IComparable comp)     {         Account compareAccount = (Account) comp;         if(balance > compareAccount.Balance)             return 1;         else if(compareAccount.Balance == balance)             return 0;         else             return -1;     } } class Sorter {      // Sort the comparable elements of an array in ascending order     public static void BubbleSortAscending(IComparable [] bubbles)     {         bool swapped = true;         for (int i = 0; swapped; i++)         {             swapped = false;             for (int j = 0; j < (bubbles.Length - (i + 1)); j++)             {                 if (bubbles[j].CompareTo(bubbles[j + 1]) > 0)                 {                     Swap(j, j + 1, bubbles);                     swapped = true;                 }             }         }     }      //Swap two elements of an array     public static void Swap(int first, int second, IComparable [] arr)     {         IComparable temp;         temp = arr[first];         arr[first] = arr[second];         arr[second] = temp;     } } class Tester {     public static void Main()     {         Account [] accounts = new Account[4];         accounts[0] = new Account(100);         accounts[1] = new Account(200);         accounts[2] = new Account(50);         accounts[3] = new Account(75);         Sorter.BubbleSortAscending(accounts);         foreach(Account tempAccount in accounts)         {             Console.WriteLine(tempAccount.Balance);         }     } } 
2:

Write three classes called Secretary, Director, and Programmer. Each of the classes contains a CalculateSalary method. For simplicity, let each of these methods write "Now calculating the salary for…" followed by the name of the class in which the method resides.

Suppose there are many objects of these classes in your program, and that they need to be stored in a collection, such as an array. How can you store them all in one array and also call the CalculateSalary of each object simply by iterating through the array and making the same method call for all objects? Write the code that implements this scenario.

A:

Exercise 2: Create a base class called Employee. Derive each of the three classes from this base class as shown in the following code:

 using System; abstract class Employee {     public abstract void CalculateSalary(); } class Secretary : Employee {     public override void CalculateSalary()     {         Console.WriteLine("Calculate salary for secretary");     } } class Director : Employee {     public override void CalculateSalary()     {         Console.WriteLine("Calculate salary for director");     } } class Programmer : Employee {     public override void CalculateSalary()     {         Console.WriteLine("Calculate salary for programmer");     } } class Tester {     public static void Main()     {         Employee [] employees = new Employee[3];         employees[0] = new Secretary();         employees[1] = new Director();         employees[2] = new Programmer();         foreach(Employee tempEmployee in employees)         {             tempEmployee.CalculateSalary();         }     } } 
3:

Extend the code of question 2 by implementing the following separate hierarchy: A base class named Building containing two instance variables called age of type int and currentValue of type decimal. Derive two classes from Building called House and OfficeBuilding. House contains an instance variable called numberOfBedrooms of type ushort and OfficeBuilding an instance variable called floorSpace of type uint.

You want to write and read objects of type Secretary and House to a file. So both of these classes must contain methods called Read and Write that (for simplicity make the Read methods write "Now reading House" and "Now reading Secretary" on the console and similarly for the Write methods) save these objects to and from a file. You want to construct just one method that accepts any object containing the Read and Write methods and will call these methods polymorphically, regardless of which type the object is. Write the code that implements this functionality.

A:

Exercise 3: The following code contains an interface called IStorable that has two abstract methods Read and Write. The Secretary and House classes both implement this interface. The Transfer method takes an argument of IStorable. We can thus send both an instance of type Secretary and of type House to this method. This is done in the Tester class. Notice that this code results in a few warnings when compiled because none of the instance variables of the classes are used (to keep the code brief).

 using System; abstract class Employee {     public abstract void CalculateSalary(); } class Secretary : Employee, IStorable {     public override void CalculateSalary()     {         Console.WriteLine("Calculate salary for secretary");     }     public void Read()     {         Console.WriteLine("Now reading secretary");     }     public void Write()     {         Console.WriteLine("Now writing secretary");     } } class Director : Employee {     public override void CalculateSalary()     {         Console.WriteLine("Calculate salary for director");     } } class Programmer : Employee {     public override void CalculateSalary()     {         Console.WriteLine("Calculate salary for programmer");     } } interface IStorable {     void Read();     void Write(); } class Building {     private int age;     private decimal currentValue; } class House : Building, IStorable {     private ushort numberOfBedrooms;     public void Read()     {         Console.WriteLine("Now reading house");     }     public void Write()     {         Console.WriteLine("Now writing house");     } } class OfficeBuilding {     private uint floorSpace; } class Tester {     public static void Main()     {         House myHouse = new House();         Secretary mySecretary = new Secretary();         Transfer(myHouse);         Transfer(mySecretary);     }     public static void Transfer (IStorable tempStore)     {         tempStore.Read();         tempStore.Write();     } } 


   


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