This is a mirror of official site: http://jasper-net.blogspot.com/

Understanding abstract classes

| Sunday, May 9, 2010
A misconception I sometimes encounter among beginner developers is the fact that some people do think that abstract classes and interfaces are the same thing. However, this is a wrong understanding. Although abstract classes and interfaces have similarities, their purpose as well as structure is different.

Abstract classes can have method/function implementations

The interface is a structure, that allows the developer to outline a set of methods, properties or and/or indexers that should be implemented in a class that implements the interface. Therefore, if an interface defines the Add and Remove methods, the inheriting class must have those methods implemented. One important aspect of interfaces is that no implementation is provided for the declared methods and functions – it all has to be done in the class that inherits the interface.

Abstract classes, on the other side, can (but not necessarily) have method/function implementations, providing default functionality for them. Therefore, once a class inherits an abstract class (in that case referenced as the base class), the developer can either use the default functionality or override the existing methods/functions.

A class can inherit multiple interfaces, but only one abstract class

C# is a language that does not support multiple inheritance. And although a single class can inherit multiple interfaces, it cannot inherit multiple abstract classes. It can be considered a limitation, but in fact it isn’t. An interface gives the freedom to develop anything that is built around a well-defined structure, while an abstract class sets a hierarchy that should be followed.

Let’s take a look at an example. Here I have an abstract class SystemDetails:

public abstract class SystemDetails
{
   public string GetDetails()
   {
       string version = Environment.OSVersion.VersionString;
       string machineName = Environment.MachineName;

       return string.Format("{0} is using {1}", version, machineName);
   }

   public void CheckTime()
   {
       Debug.Print(DateTime.Now.ToString());
   }

   public abstract void GetUserInfo();
}

Read more: DZone

Posted via email from jasper22's posterous

0 comments: