blog

Home / DeveloperSection / Blogs / Constructor in Abstract Class in C#

Constructor in Abstract Class in C#

Devesh Omar4074 09-Jun-2014

Here, I am trying to explain the use of the constructor in the abstract class.

I am Considering Shape as the abstract class and Square and rectangle as the derived class.

 public abstract class Shape
{
protected double x = 10;
protected double y = 10;
protected Shape()
{ }
protected Shape(double x, double y)
{
this.x = x;
this.y = y;
}
public abstract double AreaClaculate();
}
public class square : Shape
{
public square()
{ }
public override double AreaClaculate()
{
return x * y; // here x=10 and y=10 works, i set x=y due to square, if any we have any other shape other than square then x!=y
}
}
public class rectangle : Shape
{
public rectangle(double x, double y)
:base(x, y) // it will call Shape(double x, double y) at base class
{
}
public override double AreaClaculate()
{
return x * y; /// hre x and y will pass from runtime
}
}
static void Main(string[] args)
{
square s =new square();
double areasq= s.AreaClaculate(); // we will get 100, because x=y=100 and x*y=100
rectangle r =new rectangle(10,5); // behind the scene 10,5 are passing to shape(double x, double y) at base class
double arearect = r.AreaClaculate(); // we will get 50.
}

Updated 18-Sep-2014
I am Software Professional

Leave Comment

Comments

Liked By