What is an Interface and how is it different from Abstract Classs?

An interface in C# is a type just like class is a type.  The difference between interface and class is that an interface only contains the method headers (no implementation of methods and no attributes) where as a class contains both attributes, methods and method implementations.

Example
public interface IBankAcccount
{
    double AccountBalance();
    bool  IsActive();
}

Note that we havent declared if a method is public or  private.  In an interface all the methods are public and abstract. So, we need not specify the accessibility type in an interface.

Implementing an Interface (not inheriting an interface)Example
public Class SavingsAccount : IBankAcccount
{
   public double AccountBalance()
   {
       Console.WriteLine (“The business logic for the account balance goes here “);
    }
    bool  IsActive()
    {
           Console.WriteLine (“The business logic for the ISACTIVE goes here “);
    }
}

Abstract Class Vs Interfaces

Abstract Class Interface
Abstract Class specifies the data structure and a mixture of concrete and abstract methods. Note that an Abstract class can contain only abstract methods. In such situations we use Interface. Interfaces only have abstract methods in their definition.
When an non abstract class is derived from an abstract class, the derived class provides the implementation of abstract methods by overriding them. The derived class methods should therefore include override keyword When a class implements an interface, the class dosent override the methods. Rather the methods are defined from the scratch. and so override keyword is not part of method header.
The derived class can override all or only a few abstract methods from the base class. The derived class can also be an abstract class The class that implements interface should provide concrete implementation for all the methods defined in interface
A class can extend one base class and implement multiple interfaces

Note: 
Interfaces cannot be intatiated.
Interfaces dosent have constructors

Author: azagappan

Hi.. I am Azagu. I live in Chennai, Tamil Nadu, India. I am a .NET developer. You can reach me at azagappan at gmail.com

6 thoughts on “What is an Interface and how is it different from Abstract Classs?”

  1. Do you know if it’s possible to restrict a class implemention to the exact interface definition? That is: I want to prevent a class implementation CSomething : ISomething {} to have a public doThis() method, if it’s not in the ISomething interface, too. How to achieve this?

    Greetings,
    Hans

  2. For this i need some wht better explanation azagu….

    not a bad defin.. but not a catchy one…

Leave a reply to Hans-Juergen Philippi Cancel reply