CHAPTER 6 UNDERSTANDING INHERITANCE AND POLYMORPHISM
// The abstract base class of the hierarchy.
abstract class Shape
{
public Shape(string name = "NoName")
{ PetName = name; }
public string PetName { get; set; }
// A single virtual method.
public virtual void Draw()
{
Console.WriteLine("Inside Shape.Draw()");
}
}
Notice that the virtual Draw() method provides a default implementation that simply prints out a
message that informs you that you are calling the Draw() method within the Shape base class. Now recall
that when a method is marked with the virtual keyword, the method provides a default implementation
that all derived types automatically inherit. If a child class so chooses, it may override the method but
does not have to. Given this, consider the following implementation of the Circle and Hexagon types:
// Circle DOES NOT override Draw().
class Circle : Shape
{
public Circle() {}
public Circle(string name) : base(name){}
}
// Hexagon DOES override Draw().
class Hexagon : Shape
{
public Hexagon() {}
public Hexagon(string name) : base(name){}
public override void Draw()
{
Console.WriteLine("Drawing {0} the Hexagon", PetName);
}
}
The usefulness of abstract methods becomes crystal clear when you once again remember that
subclasses are never required to override virtual methods (as in the case of Circle). Therefore, if you
create an instance of the Hexagon and Circle types, you’d find that the Hexagon understands how to
“draw” itself correctly or at least print out an appropriate message to the console. The Circle, however,
is more than a bit confused:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Polymorphism *****\n");
Hexagon hex = new Hexagon("Beth");
hex.Draw();
236