C# .NET - What is Interface & Abstract? - Asked By Karthikeyan H on 23-Nov-11 07:30 AM

What is Interface & Abstract? please explain with simple definition.

Thanks & Regards

H.Karthikeyan
Jitendra Faye replied to Karthikeyan H on 23-Nov-11 07:32 AM

There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:

Feature

Interface

Abstract class

Multiple inheritance

A class may inherit several interfaces.

A class may inherit only one abstract class.

Default implementation

An interface cannot provide any code, just the signature.

An abstract class can provide complete, default code and/or just the details that have to be overridden.

Access Modfiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties

Core VS Peripheral

Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.

An abstract class defines the core identity of a class and there it is used for objects of the same type.

Homogeneity

If various implementations only share method signatures then it is better to use Interfaces.

If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.

Speed

Requires more time to find the actual method in the corresponding classes.

Fast

Adding functionality (Versioning)

If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.

If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.

Fields and Constants No fields can be defined in interfaces An abstract class can have fields and constrants defined

Jitendra Faye replied to Karthikeyan H on 23-Nov-11 07:32 AM
For example follow this link-

http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx
Devil Scorpio replied to Karthikeyan H on 23-Nov-11 07:33 AM
HI,

Abstract Class vs Interface

I am assuming you are having all the basic knowledge of abstract and interface keyword. I am just briefing the basics.

We can not make instance of Abstract Class as well as Interface.

Here are few differences in Abstract class and Interface as per the definition.

Abstract class can contain abstract methods, abstract property as well as other members (just like normal class).

Interface can only contain abstract methods, properties but we don’t need to put abstract and public keyword. All the methods and properties defined in Interface are by default public and abstract.

      //Abstarct Class

public abstract class Vehicles

    {

    private int noOfWheel;

    private string color;

    public abstract string Engine

    {  

      get;

      set;

    }

    public abstract void Accelerator();

    }

    //Interface

public interface Vehicles

    {

    string Engine

    {  

      get;

      set;

    }

    void Accelerator();

    }

We can see abstract class contains private members also we can put some methods with implementation also. But in case of interface only methods and properties allowed.

We use abstract class and Interface for the base class in our application.

This is all about the language defination. Now million doller question:

How can we take decision about when we have to use Interface and when Abstract Class.

Basicly abstact class is a abstract view of any realword entity and interface is more abstract one. When we thinking about the entity there are two things one is intention and one is implemntation. Intention means I know about the entity and  also may have idea about its state as well as behaviour but don’t know about how its looks or works or may know partially. Implementation means actual state and behaviour of entity.  

Enough theory lets take an example.

I am trying to make a Content Management System where content is a genralize form of article, reviews, blogs etc.

                   

CONTENT

ARTICLE

BLOGS

REVIEW

So content is our base class now how we make a decision whether content class should be Abstract class, Interface or normal class.

First normal class vs other type (abstract and interface). If content is not a core entity of my application means as per the business logic if content is nothing in my application only Article, Blogs, Review are the core part of business logic then content class should not be a normal class  because I’ll never make instance of that class. So if you will never make instance of base class then Abstract class and Interface are the more appropriate choice.

Second between Interface and Abstract Class.

CONTENT

Publish ()

ARTICLE

BLOGS

REVIEW

As you can see content having behavior named “Publish”. If according to my business logic Publish having some default behavior which apply to all I’ll prefer content class as an Abstract class. If there is no default behavior for the “Publish” and every drive class makes their own implementation then there is no need to implement “Publish” behavior in  the base case I’ll prefer Interface.

These are the in general idea of taking decision between abstract class, interface and normal class. But there is one catch. As we all know there is one constant in software that is “CHANGE”. If I made content class as Interface then it is difficult to make changes in base class because if I add new method or property in content interface then I have to implement new method in every drive class. These problems will over come if you are using abstract class for content class and new method is not an abstract type. So we can replace interface with abstract class except multiple inheritance.

CAN-DO and IS-A relationship is also define the deference between Interface and abstract class. As we already discuss Interface can be use for multiple inheritance for example we have another interface named “ICopy” which having behavior copy and every drive class have to implements its own implementation of Copy. If “Article” class drive from abstract class Content as well as ICopy then article “CAN-DO” copy also.

IS-A is for “generalization” and “specialization” means content is a generalize form of Article, Blogs, Review and Article, Blogs, Review are a specialize form of Content.

So, abstract class defines core identity. If we are thinking in term of speed then abstract is fast then interface because interface requires extra in-direction.

So as per my view Abstract class having upper-hand in compare to interface. Using  interface having only advantage of multiple inheritance. If you don’t understand the things then don’t worry because it’s my mistake because I am not able to describe the topic.

Suchit shah replied to Karthikeyan H on 23-Nov-11 07:36 AM

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.

Example of Abstract Class

abstract class WashingMachine
{
public WashingMachine()
{
// Code to initialize the class goes here.
}

abstract public void Wash();
abstract public void Rinse(int loadSize);
abstract public long Spin(int speed);
}

class MyWashingMachine : WashingMachine
{
public MyWashingMachine()
{
// Initialization code goes here.
}

override public void Wash()
{
// Wash code goes here.
}

override public void Rinse(int loadSize)
{
// Rinse code goes here.
}

override public long Spin(int speed)
{
// Spin code goes here.
}
}

Example of Interface

interface ISampleInterface
{
void SampleMethod();
}

class ImplementationClass : ISampleInterface
{
// Explicit interface member implementation:
void ISampleInterface.SampleMethod() { // Method implementation.
}

static void Main()
{
// Declare an interface instance.
ISampleInterface obj = new ImplementationClass();

// Call the member.
obj.SampleMethod();
}
}

Following are the differences between abstract and interfaces :-
√ Abstract classes can have concrete methods while interfaces have no methods implemented.
√ Interfaces do not come in inheriting chain, while abstract classes come in inheritance.
Hope it helps... and clear the understanding :)


dipa ahuja replied to Karthikeyan H on 23-Nov-11 07:43 AM

Abstract classes

An abstract method is implicitly a virtual method.

Abstract method declarations are only permitted in abstract classes.

Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ })

Interface:

Interfaces describe a group of related functionalities that can belong to any http://msdn.microsoft.com/en-us/library/0b0thckt.aspx or http://msdn.microsoft.com/en-us/library/ah19swz4.aspx. You define an interface by using the http://msdn.microsoft.com/en-us/library/87d83y5b.aspx keyword, as shown in the following example.

Interfaces consist of methods, properties, events, indexers, or any combination of those four member types. An interface cannot contain constants, fields, operators, instance constructors, destructors, or types. It cannot contain static members. Interfaces members are automatically public, and they cannot include any access modifiers.

Difference :

(1)  An abstract class may contain complete or incomplete methods. Interfaces can contain only the signature of a method but no body. Thus an abstract class can implement methods but an interface cannot implement methods.

(2)  An abstract class can contain fields, constructors, or destructors and implement properties. An interface cannot contain fields, constructors, or destructors and it has only the property's signature but no implementation.

(3)  An abstract class cannot support multiple inheritances, but an interface can support multiple inheritances. Thus a class may inherit several interfaces but only one abstract class.

(4)  A class implementing an interface has to implement all the methods of the interface, but the same is not required in the case of an abstract Class.

(5)  Various access modifiers such as abstract, protected, internal, public, virtual, etc. are useful in abstract Classes but not in interfaces.

(6) Abstract classes are faster than interfaces.

Reena Jain replied to Karthikeyan H on 23-Nov-11 09:11 AM
Hi,
The most real time example of abstract class and interface is bulding a house ,you create a class say House and then another say Shop both extend Building but you decide to make Building as an abstact class as when you create an object of the building class you don't know which kin of object it will be; will it be house or shop so the program fails and you say ah it is good that this class is made an abstract as we shouldn't create an object of this class.

Interface is a 100 % pure Abstract class means it is a class which is 100 % abstract in nature i.e 100 % unknown what it does.

  • concrete methods are explained with completed house.
  • abstract classes are explained with completed house but a little bit of work left
  • interfaces are explained with taking a building plan
Interface

In summary the Interface separates the implementation and defines the structure, and this concept is very useful in cases where you need the implementation to be interchangeable. Apart from that an interface is very useful when the implementation changes frequently.

If a class that implements an interface does not define all the methods of the interface, then it must be declared abstract and the method definitions must be provided by the subclass that extends the abstract class. In addition to this an interfaces can inherit other interfaces.

Abstract class?

Abstract classes, which declared with the abstract keyword, cannot be instantiated. It can only be used as a super-class for other classes that extend the abstract class. Abstract class is the concept and implementation gets completed when it is being realized by a subclass. In addition to this a class can inherit only from one abstract class (but a class may implement many interfaces) and must override all its abstract methods/ properties and may override virtual methods/ properties. 
refer=>http://www.geekinterview.com/talk/5254-real-time-example-abstract-class-interface.html