Review Questions



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?


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?


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.


What's wrong with the following piece of code?

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

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?


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; 

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?


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?


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.


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.


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


Why doesn't C# support multiple inheritance?


What's the problem with the following interface definition:

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

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?


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata © 2008-2017.
If you may any questions please contact us: