Abstract Class Vs Interface

Abstract Class :

We can not make instance of Abstract Class as well as Interface. It cannot be a sealed class. It can contain abstract methods, abstract property as well as other members (just like normal class).

Interface:

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. Interface are useful to achieve Multiple inheritence.

abstact class is a abstract view of any realword entity and interface is more abstract one


//Abstract class
public abstract class Calculate
{
public abstract int Result
{
get;
set;
}
public abstract void Summation(int First, int Second);
}


//Interface
public interface ICalculate
{
int Result
{
get;
set;
}
void Summation(int First, int Second);
}


//Abstract class inherited class
public class ClsAbstraction : Calculate
{
private int m_Result;
public override void Summation(int First, int Second)
{
m_Result = First + Second;
}
public override int Result
{
get { return m_Result; }
set { m_Result = value; }
}
}


//Interface implemented class
public class ClsInterface : ICalculate
{
private int m_Result;
public void Summation(int First, int Second)
{
m_Result = First + Second;
}
public int Result
{
get { return m_Result; }
set { m_Result = value; }
}
}


//Main class
public class ClsMain
{
public static void Main()
{
//Using abstarct class
ClsAbstraction objClsAbstarction = new ClsAbstraction();
objClsAbstarction.Summation(4, 5);
Console.WriteLine("Abs class result " + objClsAbstarction.Result);
//Using Interface
ClsInterface ObjClsInterface = new ClsInterface();
ObjClsInterface.Summation(5, 5);
Console.WriteLine("Interface result " + ObjClsInterface.Result);
}
}


Conclusion:

Abstract class having upper-hand in compare to interface. Using interface having only advantage of multiple inheritance.

No comments: