Inheritance, Abstract classes and Interfaces

Hi,
     C++ was one of the first language i learnt and along with that i learnt the OOPs concept of inheritance. It was pretty simple and confusing at the same time (multiple inheritance concept saw me putting a lot of efforts in :-) ). However life became simpler with multiple inheritance eliminated in .Net. However came the new concept of interfaces in .Net. For a long time i couldnt get the understanding of when to use interfaces and when to use abstract classes. Things became much clearer later, though i have seen this topic remains a big confusion for a lot of people (atleast  i have seen this in my friend circle and also in lot of posts). I am writing on this topic as my first blog, and i hope it will help to make things related to interface and abstract classes clearer.

    Let us first look at the concept of inheritance. This has come up as a wonderful concept and one of the best methods to enable code reusability in the OOPs world. Let me give an example as how inheritance can be useful. For this let me give an example of the class System.Web.UI.Page class.  For those who have worked on asp.net this will be the most familiar class. This is a built in asp.net class that contains a lot of basic funcitonality related to a Web page. Now to create the simplest web page all i have to do is to create a class that inherits from the System.Web.UI.Page class ... and here you go ... my web page is ready ..though we may need to add some stuff to make it more meaningful. But once you inherit from this class you get access to a lot of objecft like response, request, server , and also lot of utility methods and events (you will find the list of  all the methods and events on the microsoft msdn website).[1]. This is the simplest example of the use of inheritance.
 
  Let me show you another example of the advantage of inheritance. In one of our projects We had to implement a lot of functionality related to formatting, localization and also performance tracking. We had to do custom formatting of data like currency , date and also numeric fields. For this we created our own controls that inherited from standard .Net controls. to be more specific let me show you the example of currency textbox and datetextbox. In our application we have to show currency formatted in a specific manner. Rather than formatting each and every textbox manually we create control that inherited from the asp.net Textbox control and formatted the content in that inherited control. This is shown below (this is a rough example, kindly ignore any syntax or casing errors) -

  public class CurrencyTextBox : Textbox
     public shadows property Text() as string
         get
               return unformat( mybase.text) 'unformat will convert the formatted text to normal mumeric value 
         end get
         set (value as string)
               mybase.text= format(value) 'format the numeric value to proper currency format
         end set
     end property
  end class

another example for datetextbox
      public class DateTextBox: TextBox
          public sub onLoad()
               me.attributes.add("onclick","showDateCalendar()") 'add attribute to show claendar when user clicks on textbox
          end sub
      end class
   
    using the above code i got the rid of taking care of formatting each control individually or adding attributes to each individual datetextboxes.

    Another example of inheritance i can tell is having a custom base class for all my base forms.
    We have a base class that itself inherits from System.Web.UI.Page class and all my webforms inherit from this class. We have put all common functionality in this base class and avoided repeating a lot of code that would have been otherwise written in each of the individual web forms. In addition to all these when ever we want to add any common functionality to all the web forms we need to add it to only the base class.

   I hope from here you can start appreciating the value of inheritance if you havent been earlier. Now let me go into abstract classes. In some cases we have a base class, but some times few functions of it it can not be defined fully. The simplest and perhaps a common example will be the class Shape which can be classified as the base class for the class Rectangle and class Circle. Every shape has area and volume. We cannot however define the functions related to them in the class Shape (the functions can be called -- CalculateArea , CalculateVolume). We just declare these functions and not define their implementation. Such functions are called as abstract functions[2]. And the classes that contain them get called as abstract classes.
 
   Interfaces are a special case where all the functions are abstract. The advantage of interfaces is that they enable in a way multiple inheritance.[3].

   Now comes the big confusion .. When to use interfaces and when to use base classes/ abstract base classes 

   A base class would normally represent a more generalized version of its child type like a furniture as a generalized type of chair or table.

   Generally speaking a child type (here type refers to class) may belong to more than one base type(this is called as multiple inheritance) but in most of the modern languages this is avoided due to higher complexity in multiple inheritance.
  in almost all cases a type can be calssified as inheriting from one main base type. Like a human(child) is an animal(base) and a cat(child) is also an animal(base). However types can also be classified according to thier behaviours like a human can move and a car can also move. However since most languages dont allow inheritance we define behaviours by implementing interfaces. in  addition implementing an interface will guarantee that a certain behaviour is present.

   for example i have different classes each that calculate specific type of bills (like waterbill, electricitybill, telephonebill) 
   i have another function that calculates the  total of all bills. this function takes an array of objects of bill types. It then calls calculate method  of each object and add the returned billvalue to calculate the total. To ensure that all these objects have the method calculate these inherit from the interface IBill and have to implement its method calculate. The code will help to shed more light on the same
   public interface IBill{
     int calculate();
}

  //other classes inherit from the interface
  public class waterbill:IBill{
   public int calculate(){ //calculates bill and returns}
}
 public class electricitybill:IBill{
   public int calculate(){ //calculates bill and returns}
}
 public class telephonebill:IBill{
   public int calculate(){ //calculates bill and returns}
}
   

then a class called expenses has a function calculateexpenses

public class expenses{
   public void displayExpenses(IBill []obj)
   {

     int tot=0;
     for (int i=0;i<obj.length;i++){
          tot+= obj[i].calculate(); //this can be called as all objects implement the ibill interface 
       }

    //finally print the total
   }
}
  

as you can see there is also no need to type cast and the presence of calculcate method is guaranteed.

I hope this first blog of mine helps. This has been a topic of lot of debate. I will try to come up with more articles on the same
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

[1] I wonder if we can create a web page in asp.net without inheriting from the System.Web.UI.Page class. I am sure we can though i cant remember it now
[2] For syntax of declaring abstract functions and classes please refer to msdn
[3] For more info on interfaces refer to the msdn

Cheers
Sohail Sayed

3 Comments

  • Hi, This is an exelent and helpfull article.

  • Hi, This is really helpfull to understand some of the basic oops concepts. Thanks.

  • Hi friend I m facing a tough situation in oops concept.

    Say your Class Class A has 4 methods(M1,M2,M3,M4) .I m creating a Class B(Derived Class) which inherits Class A and now I m adding a method M5 in Class B.

    In class B I have acess to all 4 methods and Method M5

    Rather than inheriting Class A I could Have easily added a new method (M5) in my base Class A.

    So what is the use of inheritance.

    Can Any One Explain

    Regards

    Chandrakant

Comments have been disabled for this content.