Hi,
Before knowing when to use abstract and interface, first you should know what are the difference between them.
For that go thru the below link
http://www.dotnetuncle.com/Difference/4_abstract_class_interface.aspx
In the below code there is an abstract class named Shape. So when inherited by rectangle class it uses only Length and breadth i.e. L and B variables in Shape class & also implements the methods Area and Circumference.While Circle class uses only Radius R.
Using interfaces we cannot declare variables (but u may ask we can Properties - Yes).
But Using Abstract class we can also define non-abstract class methods.What i mean by these lines is if I implement all the methods of Circle inside abstract class without using Abstract keyword then we need not implement these methods in Circle class while inheriting Shape class.So, use Interfaces when you think that all the classes inheriting the Interface use all the methods defined in an Interface or else go for abstract where there is flexibility.
abstract class Shape
{
protected double L, B, R;
public abstract double Area();
public abstract double Circumference();
public double CircleArea()
{
return Math.PI * R * R;
}
public double CircleCircumference()
{
return 2 * Math.PI * R;
}
public void GetR()
{
Console.Write("Enter Radius : ");
R = double.Parse(Console.ReadLine());
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OOPS
{
abstract class Shape
{
protected double L, B, R;
public abstract double Area();
public abstract double Circumference();
}
class Rectangle1 : Shape
{
public void GetLB()
{
Console.Write("Enter Length : ");
L = double.Parse(Console.ReadLine());
Console.Write("Enter Breadth : ");
B = double.Parse(Console.ReadLine());
}
public override double Area()
{
return L * B;
}
public override double Circumference()
{
return 2 * (L + B);
}
}
class Circle1 : Shape
{
public void GetR()
{
Console.Write("Enter Radius : ");
R = double.Parse(Console.ReadLine());
}
public override double Area()
{
return Math.PI * R * R;
}
public override double Circumference()
{
return 2 * Math.PI * R;
}
}
class AbstractMethods
{
static void Calculate(Shape S)
{
Console.WriteLine("Area : {0}", S.Area());
Console.WriteLine("Circ : {0}", S.Circumference());
}
static void Main()
{
Rectangle1 R = new Rectangle1();
R.GetLB();
Calculate(R);
Circle1 C = new Circle1();
C.GetR();
Calculate(C);
}
}
}
Please let me know if you need an additional explanation.
Regards,
Prathap.
amanueljoseph-9523, if this helps please login to Mark As Answer. | Alert Moderator