Abstract class and interface in C# -When to use?

Posted by krrishbiju-15589 under C# on 9/10/2013 | Points: 10 | Views : 87738 | Status : [Member] | Replies : 11
Hi

I know how to use both Abstract class and interface in C#

but i just want to know the what is the problem in using Abstract in place of interface and viceversa.

I know the coding part but wanted to know the problem in using the above in the wrong place.

Any could you please explain me the above with scenarios..




Responses

Posted by: Bandi on: 9/10/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down
Why we have Abstract class and Interfaces means...
1) C# doesn't support Multiple inheritance ( means deriving a class from more than one class)... If your application supposed to have more than one class features at a time, we can inherit one class and other interface as follows:
Public class ChildClass : BaseClass, BaseInterface

{
}


2) An abstract class can have shared state or functionality. An interface is only a promise to provide the state or functionality. A good abstract class will reduce the amount of code that has to be rewritten because it's functionality or state can be shared. The interface has no defined information to be shared

Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif

krrishbiju-15589, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: krrishbiju-15589 on: 9/10/2013 [Member] Starter | Points: 25

Up
0
Down
Good Chandu....
Can you please explain with more practical example like when and why we use interface and abstract class.
regards
krrish

krrishbiju-15589, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Nismeh on: 9/10/2013 [Member] Starter | Points: 25

Up
0
Down
Hi Krrish,

Main difference between them is if we are using interface than we need to implement all methods defined into interface but if we are using abstract class than we can use methods as per requirement. On base of this difference you can decided what to use and when to use.

Other difference is we can even write concrete method into abstract class but we can't do same in interface.

Hope these two are main reasons which can lead us to decide what to use. And ya there are other differences.

IT KNOWLEDGE IS APPLIED KNOWLEDGE
So Just Do It

krrishbiju-15589, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Bandi on: 9/10/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down
The choice of whether to design your functionality as an interface or an abstract class (a MustInherit class in Visual Basic) can sometimes be a difficult one. An abstract class is a class that cannot be instantiated, but must be inherited from. An abstract class may be fully implemented, but is more usually partially implemented or not implemented at all, thereby encapsulating common functionality for inherited classes
An interface, by contrast, is a totally abstract set of members that can be thought of as defining a contract for conduct. The implementation of an interface is left completely to the developer.

Both interfaces and abstract classes are useful for component interaction. If a method requires an interface as an argument, then any object that implements that interface can be used in the argument. For example:
' Visual Basic

Public Sub Spin (ByVal widget As IWidget)
End Sub
// C#
public void Spin (IWidget widget)
{}


This method could accept any object that implemented IWidget as the widget argument, even though the implementations of IWidget might be quite different. Abstract classes also allow for this kind of polymorphism, but with a few caveats:
•Classes may inherit from only one base class, so if you want to use abstract classes to provide polymorphism to a group of classes, they must all inherit from that class.
•Abstract classes may also provide members that have already been implemented. Therefore, you can ensure a certain amount of identical functionality with an abstract class, but cannot with an interface.

Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.
•If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
•If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
•If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
•If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.

I will try to provide you samples soon ...
Refer this link
http://programmers.stackexchange.com/questions/41740/when-to-use-abstract-classes-instead-of-interfaces-with-extension-methods-in-c

Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif

krrishbiju-15589, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Bandi on: 9/10/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down
Sample example:
class Program

{
private interface IVehicle
{
void Move();
}

private abstract class Car : IVehicle
{
public abstract void Move();

protected void Drive(string name)
{
Console.WriteLine("Drive " + name);
}
}

private class Toyota : Car
{
public override void Move()
{
Drive("Toyota");
}
}

private class Ford : Car
{
public override void Move()
{
Drive("Ford");
}
}

private abstract class Bicycle : IVehicle
{
public abstract void Move();

protected void Peddle(string name)
{
Console.WriteLine("Peddle " + name);
}
}

private class Cannondale : Bicycle
{
public override void Move()
{
Peddle("Cannondale");
}
}

private class Bianchi : Bicycle
{
public override void Move()
{
Peddle("Bianchi");
}
}

private static void MoveDownStreet(List<IVehicle> vehicles)
{
Console.WriteLine(String.Empty);
Console.WriteLine("Move IVehicles down the street");
vehicles.ForEach(v => v.Move());
}

private static void MoveDownLeftLane(List<Car> cars)
{
Console.WriteLine(String.Empty);
Console.WriteLine("Move Cars down left lane");
cars.ForEach(c => c.Move());
}

private static void MoveDownBikeLane(List<Bicycle> bikes)
{
Console.WriteLine(String.Empty);
Console.WriteLine("Move Bicycles down bike lane");
bikes.ForEach(b => b.Move());
}

static void Main(string[] args)
{
var allvehicles = new List<IVehicle>();
allvehicles.Add(new Toyota());
allvehicles.Add(new Ford());
allvehicles.Add(new Cannondale());
allvehicles.Add(new Bianchi());

MoveDownStreet(allvehicles);
MoveDownLeftLane(allvehicles.Where(v => v.GetType().BaseType == typeof(Car)).Cast<Car>().ToList());
MoveDownBikeLane(allvehicles.Where(v => v.GetType().BaseType == typeof(Bicycle)).Cast<Bicycle>().ToList());
}
}

In the above example, the declaration of Move() as an abstract method in both the Car and Bicycle abstract classes count as an implementation as far as IVehicle is concerned. Yet, they are still not implemented as concrete methods as far as the abstract classes are concerned.
Refer these links:
http://tutorials.csharp-online.net/Should_I_use_an_abstract_class_or_an_interface%3F
http://channel9.msdn.com/Forums/Coffeehouse/Abstract-class-vs-Interface-When-to-use-them-and-which-scenario


Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif

krrishbiju-15589, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Kmandapalli on: 9/11/2013 [Member] Silver | Points: 25

Up
0
Down
Hi,

Abstract Class:
An abstract class is a special kind of class that cannot be instantiated. So, why we need a class that cannot be instantiated? An abstract class is only to be inherited from. In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain common behavior or properties across multiple classes who inherit the abstract class.

Declaration:
public abstract class Employee
{
public virtual String CalculateSalary()
{
//Can provide default behavior
}
}

Interface:
An interface is an entity that is defined by the word Interface. An Interface only contains signature of the methods whose implementation is to be provided by the classes who implements that Interface.

Declaration:
public interface IEmployee
{
String CalculateSalary(); //Only Signature can be specified not even access modifiers.
}

Differance between abstract class and interface:
Abstract Class Interface
Multiple Inheritance Since .NET does not support multiple inheritance, A class can implement multiple Interfaces.
So A class can inherit only one Abstract Class

Default Behavior In abstract class you can provide default behavior of a You cannot provide a default behavior in interfaces.
function, so that even if child class does not provide its Interfaces only allow you to provide signature of the
own behavior, you do have a default behavior to work method.
with. Eg. Abstract classes of framework,
even if you don’t provide your own behavior,
they have a default behavior.

Access Modifiers You can access modifiers to the methods present in You cannot provide access modifiers to the methods
abstract class. present in interface.


Scenario

Now, lets talk about a single scenario that I hope it will make you understand the situations where to use what.

Lets Assume you need to make three classes, first is CAR, second is MAN, third is WOMAN. Now you need a function in each of them to define how they Move. Now all three can move but CAR moves entirely in different way than MAN and WOMAN. So here we use an Interface IMOVEMENT and declare a function MOVE in it. Now all three classes can inherit this interface. So the classes goes like this.

public interface IMovement
{
void Move();
}

public class Car : IMovement
{
public void Move()
{
//Provide Implementation
}
}

public class Man : IMovement
{
public void Move()
{
//Provide Implementation
}
}

public class Woman : IMovement
{
public void Move()
{
//Provide Implementation
}
}

But, since MAN and WOMAN walk in similar way, so providing same behavior in two different methods will be code redundancy, in simpler words code is not re-used. So we can now define a Abstract Class for Human Beings movements, so this class can be HUMANBEINGMOVEMENT. Also the same can be applied to CAR class, since there are lot of manufactures for cars and all cars move in similar way so we can also define a abstract class for Cars movement which can be CARSMOVEMENT. So our refactored code will be .

public interface IMovement
{
void Move();
}

public abstract class CarsMovement : IMovement
{

public virtual void Move()
{
//default behavior for cars movement
}
}

public class SuzukiCar : CarsMovement
{
public override void Move()
{
//Provide Implementation
}
}

public abstract class HumanBeingMovement : IMovement
{

public virtual void Move()
{
//default behavior for human being movement
}
}

public class Man : HumanBeingMovement
{
public override void Move()
{
//Provide Implementation
}
}

public class Woman : HumanBeingMovement
{
public override void Move()
{
//Provide Implementation
}
}

Now as you can see, an hierarchy is appearing now every human being can inherit from our HUMANBEINGMOVEMENT class for the move method and all types of cars can inherit from our CARSMOVEMENT class for the move method.

Mark as answer if satisfied...........


Regards,
Shree M.


Kavya Shree Mandapalli

krrishbiju-15589, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Satyapriyanayak on: 9/12/2013 [Member] [MVP] Silver | Points: 25

Up
0
Down
Abstract class


A class that cannot be instantiated. An abstract class is a class that must be inherited and have the methods overridden. An abstract class is essentially a blueprint for a class without any implementation.

An abstract class is a special kind of class that cannot be instantiated. It normally contains one or more abstract methods or abstract properties. It provides body to a class.

Interface

An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body.

It's an abstract class with public abstract methods all of which must be implemented in the inherited classes.

In which Scenario you will go for Interface or Abstract Class?

Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. Even though class inheritance allows your classes to inherit implementation from a base class, it also forces you to make most of your design decisions when the class is first published.
Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.

Difference Abstract class vs Interface

Abstract Class:-
1) An abstract method is created by specifying the abstract type modifier.
2) An abstract method contains no body.
3) An abstract method is not implemented by the base class.
4) An abstract method is automatically virtual.
5) A derived class must override it.
6) Abstract class can have modifiers for methods,properties etc.,
7) An abstract class can implement a property.
8) The abstract modifier cannot be applied to static methods.
9) Properties can also be abstract.
10) A class containing abstract methods must be declared as abstract with the abstract specifier.
11) There can be no objects of an abstract class.
12) If a derived class doesn't implement all of the abstract methods in the base class, then the derived class must also be specified as abstract.
13) An abstract class can inherit from a class and one or more interfaces.
14) An abstract class can implement code with non-Abstract methods.
15) Abstract class can have constant and fields.
16) An abstract class can have constructors or destructor's.
17) An abstract class cannot be inherited from by structures.
18) An abstract class cannot support multiple inheritance.
19) 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.

Interface:-
1) Interfaces cannot be instantiated directly.
2) Interfaces can contain events, method, indexer and properties.
3) An Interface can contain property definitions.
4) Interfaces contain no implementation of methods.
5) Classes and Structs can implement more than one interface.
6) An Interface can be inherited from by structures.
7) An interface itself can inherit from multiple interfaces (Interface can support multiple
inheritance).
8) An abstract class can implement a property.
9) 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 this post helps you mark it as answer
Thanks

krrishbiju-15589, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Shefalisharma on: 8/20/2015 [Member] Starter | Points: 25

Up
0
Down
A question that arises is C# does not support multiple inheritence and so do the abstract classes. and both of the classes can be inherited once .
What is the major difference b/w the normal class and abstract class.
Why should we use abstract class. we can define the common behavior in the normal class and inherit the same?


krrishbiju-15589, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Shreedar on: 8/20/2015 [Member] Starter | Points: 25

Up
0
Down
Abstract class:
*Abstract class can contain both abstract methods and non abstract methods.
*If a class contains at least one abstract method then that class must be declared as abstract class.
*Abstract class can inherit from another abstract class and can inherit from more than one interface.
*Abstract methods must be implemented in derived class.
*Object cannot be created for abstract classes, reference can be created.

public abstract class myabstract: IA, IB //IA and IB are two interfaces
{
public abstract viod m1(); //abstract method
public void m2() //non abstract method
{
//some logic
}
}

Interface:
*Interface contain only abstract methods, which are public abstract by default.
*Interface can implement another interface but cannot implement abstract class.
*Object cannot be created for interface, reference can be created.

public interface ISample:IMysample
{
void mymethod();
void mymethod2();
}


Regards

Sridhar Thota.
www.dotnet-sridhar.blogspot.com

krrishbiju-15589, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Shreedar on: 8/20/2015 [Member] Starter | Points: 25

Up
0
Down
Hi Shefalisharma.

Why we use interface?
Ans)C# does not support multiple inheritance, because one normal class cannot have more than one parent class.
But this can be achieved by using interfaces, since a class can implement more than one interface thus achieving multiple inheritance.

Why we use abstract class?
Ans)When you want a method must and should get overridden in every child class, then we declare that method as abstract method. If a class contains at least one abstract method then that class should be declared as abstract class.


Regards

Sridhar Thota.
www.dotnet-sridhar.blogspot.com

krrishbiju-15589, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Shefalisharma on: 8/21/2015 [Member] Starter | Points: 25

Up
0
Down
I am talking about normal class and abstract class . Interface is a separate entity which support multiple implementation.

to write abstract methods which can be overridden in the derived class ,we can use virtual methods which can also be overridden.

Why we should use abstract class instead of normal class? what would be the scenario where we can't use normal class and can only use abstract class.




krrishbiju-15589, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response