.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Comparing Interfaces and Abstract Classes

Posted By:Shashi Ray       Posted Date: February 25, 2009    Points: 10    Category: C#    URL: http://www.dotnetspark.com  

Comparing Interfaces and Abstract Classes


When you create an interface, you are creating a set of one or more method definitions that you must write in each class that implements that interface. There is no default method code generated: you must include it yourself. The advantage of interfaces is that they provide a way for a class to appear to be part of two classes: one inheritance hierarchy and one from the interface. If you leave an interface method out of a class that is supposed to implement that interface, the compiler will generate an error.


When you create an abstract class, you are creating a base class that might have one or more complete, working methods, but at least one that is left unimplemented, and declared abstract. You can't instantiate an abstract class, but must derive classes from it that do contain implementations of the abstract methods. If all the methods of an abstract class are unimplemented in the base class, it is essentially the same as an interface, but with the restriction that you can't make a class inherit from it as well as from another class hierarchy as you could with an interface. The purpose of abstract classes is to provide a base class definition for how a

set of derived classes will work, and then allow the programmer to fill these implementations in differently in the various derived classes.


Another related approach is to create base classes with empty methods. These guarantee that all the derived classes will compile, but that the default action for each event is to do nothing at all. Here is a Shape class like that:


public class NullShape {

protected int height, width;

protected int xpos, ypos;

protected Pen bPen;


public Shape(int x, int y, int h, int w) {

width = w;

height = h;

xpos = x;

ypos = y;

bPen = new Pen(Color.Black );



public void draw(Graphics g){}


public virtual float getArea() {

return height * width;




Note that the draw method is now an empty method. Derived classes will compile without error, but they won't do anything much. And there will be no hint what method you are supposed to override, as you would get from using an abstract class.


Shashi Ray

 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend