Changes

Jump to: navigation, search

Understanding C Sharp Abstract Classes

2,050 bytes added, 17:08, 22 January 2008
Deriving from an Abstract Class
}
}
</pre>
 
== The Difference Between abstract and virtual Members ==
 
So far we have only looked at ''abstract'' class memebers. As discussed above an abstract member is not implemented in the base class and ''must'' be be implemented in derived classes in order for the class to compile.
 
Another type of member is a ''virtual'' member. A member defined as ''virtual'' must be implemented in the base class, but may be optionally overrided in the derived class if diferent bavior is required. For example, the following example implements a virtual method in the ''Talk'' class:
 
<pre>
using System;
 
class Hello
{
 
 
public abstract class Talk
{
public abstract void speak();
 
 
public virtual void goodbye()
{
Console.WriteLine("Talk class says goodbye!");
 
}
}
 
public class SayHello : Talk
{
public override void speak()
{
Console.WriteLine("Hello!");
}
}
 
static void Main()
{
SayHello hello = new SayHello();
hello.speak();
hello.goodbye();
}
}
</pre>
 
When executed, the ''goodbye()'' method in the Talk class will be executed resulting in the following output:
 
<pre>
Hello!
Talk Class says goodbye!
</pre>
 
If we decide that the default ''goodbye()'' method provided by the Talk class is not suitbale for the requirements of the ''SayHello'' subclass we can simpyl implement our own version of the method using the override modifier:
 
<pre>
using System;
 
class Hello
{
 
 
public abstract class Talk
{
public abstract void speak();
 
 
public virtual void goodbye()
{
Console.WriteLine("Talk class says goodbye!");
 
}
}
 
public class SayHello : Talk
{
public override void speak()
{
Console.WriteLine("Hello!");
}
 
public override void goodbye ()
{
Console.WriteLine ("SayHello Class says goodbye!");
}
}
 
static void Main()
{
SayHello hello = new SayHello();
hello.speak();
hello.goodbye();
}
}
</pre>
 
Now when we execute our program the ''SayHello'' implementation of the ''googbye()'' method will be called:
 
<pre>
Hello!
SayHello Class says goodbye!
</pre>

Navigation menu