Click here to Skip to main content
Licence CPOL
First Posted 1 Jun 2009
Views 52,701
Bookmarked 93 times

Abstract Class Vs Interface

By | 10 Jun 2009 | Article
An article on motto behind Abstract class and Interface, when to use Abstract class and Interface

Background

Years ago when I was interviewed, I had been asked to explain the differences and main motto behind Abstract class and Interfaces. Interviewers seemed unsatisfied by the answers I gave, it seemed like they wanted to hear some specific points. I also had many doubts and I failed to express the concepts programmatically in what scenario I would choose to use these. I Googled and got disappointed. Much of R&D and also the fruit of experience made me understand these concepts. After years, I am still unable to find an article that explains when to use Abstract class and when to use Interfaces with a good example.

This is the reason I thought of writing this article hoping to share the most basic concepts of Object Oriented Programming. For a mature programmer, it is important to give a logical explanation and I suggest the candidates be prepared with some real world example (a bit of pseudo code) to present in an interview. The code comes handy when you fall short of words.

I am assuming you have all the basic knowledge of how to code Abstract class and Interfaces. I will skip the coding part as I think MSDN has given its best. There are thousands of articles on the web which explain how to code, advantages and language differences. I am focusing on when to use Abstract class and when to use Interfaces.

For more details on these concepts, please go through the references at the end of this article.

Contents

  1. Brief Introduction
  2. Motto behind Abstract class and Interface
  3. Few advantages
  4. When to use Abstract class and when to use Interface
  5. Conclusion
  6. References

Brief Introduction

Abstract Class

These classes are either partially implemented, or not at all implemented.

  • This class can contain declarations and also implementations. 
  • We cannot make instance of Abstract class. We must inherit to use this class.
  • A non-abstract class derived from an Abstract class must include implementations for all inherited abstract methods.
  • Abstract class can contain abstract methods, abstract property as well as other members (just like normal class).

Interface

Interface is a pure abstract entity:

  • It contains only the declaration.
  • We cannot make instance of an Interface. We must inherit to use Interface.
  • A class which implements the interface should implement all the members of an Interface.
  • Members of an Interface are always public.

Few Advantages

An advantage of Abstract class over Interface

If you want to have additional functionalities for the interface, you must implement the new ones in all of the classes that implement the changed interface. The code will not work until you make the change. But if you want to have additional functions to the Abstract class, you can have default implementation. Your code still might work without many changes.

An advantage of Interface over Abstract class

A class can inherit multiple interfaces but can inherit only one class.

Now let us discuss the most important part - when to use Abstract and when to use Interface.

When to Use Abstract and When to Use Interface

Let me explain it with reference to the scenario.

Let us take a classification called Human. As it is a very general classification, I can put all the Human related common data in Abstract class. These common data could be First Name, Last Name, Gender, Education, Occupation, Residence, etc. with some functions as virtual (or overridable), e.g., an occupation which differs from human to human.

Aim of Interface: We want the implementing object to acquire this ability.
Aim of Abstraction: We want the derived object to belong to some group. Abstraction gives the Identity to the derived object.

The sentence "Object A is a Human" is more meaningful than the sentence "Object A is an object which has the ability to walk." (Human can walk, an animal, a bird, a machine - consider it is a robot ... that can also walk.)

Why I chose interfaces IEat, IWalk, IDance and ISing

I may want Object A to walk in the morning, to eat in the afternoon or to dance in the evening, or I may not be aware at a particular time what these objects should be doing. The capability of Object A at a particular time is unknown to me. Also every derived object may need not posses the quality of walking, or dancing, or singing. An infant cannot walk, as you know everybody cannot dance and sing. So I created these interfaces so that I can define the combination of these capabilities for different objects explicitly.

Refer to the image below for a more clearer view.

Take an example of .NET interfaces IDisposable or IComparable. We implement these interfaces only if necessary. We implement IDisposable mostly when we want to handle COM components and IComparable to compare and sort the objects in an Array.

If you want your class to have an Identity of Form, you must inherit Form class and you can add the ability to dispose, by implementing IDisposable, only if you want to dispose it manually.

Polymorphic Behavior

As I told you, interface adds to the capability of an Object, this means I can have an Object which eats while walking, and the same Object which can dance, and also sing well. This gives polymorphic behavior (single object – multiple capabilities) to the object.

Let me explain this with the help of code.

namespace TestAbstractVsInterface
{
    //Abstract class

    abstract class AbstractHuman
    {
        public abstract string name { get; set;}
        public abstract string qualification { get; set;}
        
        //Remaining code goes here
        //.
        //.
        //.
        //.
    }

    //Interfaces

    interface IEat
    {
        void eat();
    }

    interface ISing
    {
        void sing();
    }

    interface IWalk
    {
        void walk();
    }

    interface IDance
    {
        void dance();
    }

    //Class which inherits abstract class and implements interfaces

    class MyClass : AbstractHuman, IEat, ISing, IWalk, IDance
    {      
        private string strName = "Arati Kadi";
        private string strQualification = "";
        
        public override string name
        {
            get { return strName; }
            set { name = value; }
        }

        public override string qualification
        {
            get { return strQualification; }
            set { name = value; }
        }

        public void eat()
        { 
            //Related code
        }

        public void sing()
        { 
            //Related code
        }

        public void walk()
        { 
            //Related code
        }

        public void dance()
        { 
            //Related code
        }

//The code snippet below checks by what type class could be //accessed as.

        public void getAbilities()
        {
            if (this is IEat)
                Console.WriteLine("MyClass can eat");                
            if (this is IWalk)
                Console.WriteLine("MyClass can walk");                
            if (this is ISing)
                Console.WriteLine("MyClass can sing");              
            if (this is IDance)
                Console.WriteLine("MyClass can dance");               
        }        
    }  

    //Test Myclass

    class testClass
    {
        MyClass objMyClass = new MyClass();

        public void test()
        {
            objMyClass.getAbilities();
        }
    }

 }

Output

MyClass can eat                  
MyClass can walk                
MyClass can sing
MyClass can dance

Technically speaking, here the class is used as more than one type. It is used as four Interface Types. It can also be used as its own type and also the type of its base class.

Reusability

Let us consider the same abstract Human class which has the virtual function Eat instead of an Interface IEat.

Now I want to create a class called Bird. As a Bird can also eat, I want to reuse the function which is already there in Human class. Suppose, just because abstract Human class has the function to eat, I cannot derive a Bird class from that. I will tend to change the Bird's identity by doing so, or I may load unnecessary properties to the Bird that could be an education, or employment, or may be the last name. Even worse I may need to change the abstract Human class so as to include the common behaviors of Bird category. This is totally senseless and messes up the class and objects. Instead, I can have another Abstract class for Birds and choose to have an interface called IEat, which could be implemented by an object of Human and also an object of Bird.

Again I want to mention .NET interfaces IDisposable, IComparable (and many). These are available in System namespace and you are reusing to implement with required classes.

Conclusion

  • Abstract class gives an Identity to the derived object.
  • Interface extends the ability of an object.
  • Interfaces give polymorphic behavior.
  • Abstract class also gives polymorphic behavior. But it is more meaningful to say that Abstract class simplifies versioning, as the base class is flexible and inheriting class can create many versions of it by additional functions and also by implementing Interfaces.
  • Interfaces and Abstract Classes both promote reusability.

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Arati Kadi

Software Developer

India India

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 Pinmemberkailas_khule21:08 20 May '12  
GeneralMy vote of 5 PinmemberPratyaksh19:04 10 May '12  
QuestionQuestion Pinmemberjaimin8523:51 10 Apr '12  
GeneralMy vote of 5 PinmemberAmul V V Wayangankar21:07 11 Jan '12  
GeneralMy vote of 5 PinmemberMember 32323801:49 17 Oct '11  
GeneralMy vote of 5 PinmemberAmit kumar pathak0:56 9 May '11  
GeneralMy vote of 5 Pinmemberekiran23:55 27 Feb '11  
GeneralRE:Great Article Pinmemberdhakirhussain22:50 2 Oct '10  
GeneralMy vote of 5 PinmemberMishri0119:32 24 Aug '10  
GeneralProblem in viewstate of a Textbox Pinmemberabhishekdikshit1123:15 4 Jul '10  
GeneralI have my own way, Pinmemberring_05:36 20 May '10  
GeneralVery basic and very good with examples Pinmembergogsthecoder21:54 7 Dec '09  
GeneralSimply superb article. Pinmembermanda venu0:27 10 Nov '09  
GeneralExample implementing the interface PinmemberTjie Pouw20:41 22 Oct '09  
QuestionNot an interview question! PinmemberPratik.Patel20:09 18 Aug '09  
GeneralThanks Arti PinmemberhrishiS19:34 29 Jul '09  
GeneralThanks Arti PinmemberMember 472791123:51 24 Jul '09  
GeneralRe: Thanks Arti PinmemberMember 795541320:00 25 May '11  
GeneralGood article PinmemberDonsw17:46 18 Jul '09  
GeneralMy vote of 2 Pinmembergglaze2:43 17 Jun '09  
GeneralTeacher's pride. Pinmemberkanu@adatapost20:18 10 Jun '09  
GeneralGood Article PinmemberSaurabh_Saxena8:57 10 Jun '09  
GeneralPlease pay attention to word choices Pinmemberwmjordan16:35 9 Jun '09  
Generalinterface = contract PinmemberPCoffey8:33 1 Jun '09  
GeneralRe: interface = contract PinmemberArati Kadi19:38 1 Jun '09  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 11 Jun 2009
Article Copyright 2009 by Arati Kadi
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid