Difference between Virtual and Abstract Methods

Virtual methods have an implementation and provide the derived classes with the option of overriding it. Abstract methods do not provide an implementation and forces the derived classes to override the method.

So, abstract methods have no actual code in them, and subclasses HAVE TO override the method. Virtual methods can have code, which is usually a default implementation of something, and any subclasses CAN override the method using the override modifier and provide a custom implementation.

 public abstract class Talk
 {
 public abstract void speak();


 public virtual void goodbye()
 {
 MessageBox.Show("Whats up");
 }
 }

 public class SayHello : Talk
 {
 public override void speak()
 {
 MessageBox.Show("Hello!");
 }
 }

 SayHello sys = new SayHello();
 sys.goodbye();
---------------------------------------------------------
 SayHello sys = new SayHello();
 sys.goodbye();

Print......
Whats up

					
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: