CHAPTER 6 UNDERSTANDING INHERITANCE AND POLYMORPHISM
}
Circle cir = new Circle("Cindy");
// Calls base class implementation!
cir.Draw();
Console.ReadLine();
Now consider the following output of the previous Main() method:
***** Fun with Polymorphism *****
Drawing Beth the Hexagon
Inside Shape.Draw()
Clearly, this is not a very intelligent design for the current hierarchy. To force each child class to
override the Draw() method, you can define Draw() as an abstract method of the Shape class, which by
definition means you provide no default implementation whatsoever. To mark a method as abstract in
C#, you use the abstract keyword. Notice that abstract members do not provide any implementation
whatsoever:
abstract class Shape
{
// Force all child classes to define how to be rendered.
public abstract void Draw();
...
}
Note Abstract methods can only be defined in abstract classes. If you attempt to do otherwise, you will be
issued a compiler error.
Methods marked with abstract are pure protocol. They simply define the name, return type (if any),
and parameter set (if required). Here, the abstract Shape class informs the derived types “I have a method
named Draw() that takes no arguments and returns nothing. If you derive from me, you figure out the
details.”
Given this, you are now obligated to override the Draw() method in the Circle class. If you do not,
Circle is also assumed to be a noncreatable abstract type that must be adorned with the abstract
keyword (which is obviously not very useful in this example). Here is the code update:
// If we did not implement the abstract Draw() method, Circle would also be
// considered abstract, and would have to be marked abstract!
class Circle : Shape
{
public Circle() {}
public Circle(string name) : base(name) {}
public override void Draw()
{
Console.WriteLine("Drawing {0} the Circle", PetName);
237