Wednesday, May 30, 2007

Abstract Class VS Interfaces

As i was going thru some of my reviewers, I noticed that there are two types of classes in C# wherein they can't be instantiated and if you inherit either one of them, you should implement their methods. This are the abstract class and the Interface.

Now in my opinion this are the difference between the two:
  • An abstract class can have constructors while an Interface can't - Interfaces acts just like a blueprint of class except that it don't have any implementations, so what's the need of having a constructor if you wouldn't put in any implementation on it.
  • An abstract class can have concrete methods an Interface can't - Like a normal class an abstract class can have fields, concrete methods and constructors. An abstract class also could have access modifiers, again, just like a normal class.
  • You can do multiple inheritance with an Interface however this is not possible in an abstract class - an abstract class is like an incomplete class, and C# does not support multiple class inheritance, it would be a disaster.

So to sum it all up an abstract class is really like a class except that some of it's methods are not implemented or defined however an Interface is like a blueprint or a contract, it's methods should be implemented in the deriving class. Another thing is when you implement the methods of an abstract class you should add the override modifier to it, in interfaces you don't need to add it.

No comments: