Keywords : Virtual vs Override vs New

The purpose of this article is to explain the difference between  Virtual, Override and New keywords.

These three keywords have one thing in common is that they all are used to achieve some sort of polymorphism technique in OOO design.

1. Virtual :  This keyword is used for methods when we want the methods in base class  to be overridden and give different implementation to it.

Example: In the above code sample, if we don’t want the default color “Red” then we can override in the base class to provide a different color “Black”.

public class Shape {
  private string _color = null;
  public virtual void DrawColor() {
    _color = "Red";
  }
}
public Class CircleShape : Shape {
  private string _color = null;
  public override void DrawColor() {
    _color = "Black";
  }
}

2. Override : This keyword is used to change the implementation of base class method in the derived class methods. The above code snippet shows the usage of “override” keywrod.

3. New : This keyword is used to change the behavior of the base class method when there is no Virtual keyword is provided.

public class Shape {
  private string _color = null;
  public void DrawColor() {
    _color = "Red";
  }
}
public Class CircleShape : Shape {
  private string _color = null;
  public new void DrawColor() {
    _color = "Black";
  }
}

Note: The keyword “new” is not recommended to be used as this will hide the implementation of base class.

Advertisements

One thought on “Keywords : Virtual vs Override vs New

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