+92 332 4229 857 99ProjectIdeas@Gmail.com

Abstract Classes (C#.net)


Abstract Classes In C#.net:
Are those classes which can’t be instantiated means you can’t create their object. Generally, an abstract class is a class which contains both proper implementations of its public methods or only the prototypes of methods also. And a class which extends this abstract class, now its responsibility to provide the implementations of those methods which are left and if it provides the proper implementations of those methods then we call this class (which extending the abstract class) a concrete class and if it don’t provide then this class have to declare itself an abstract, otherwise if it don’t declare itself an abstract then compiler wont compile it. Whenever there is a "IS-A relationship" use this.

Code

public abstract class Shape
{
    private int area;

    public int Area
    {
        get { return area; }
        set { area = value; }
    }

    private int circumference;

    public int Circumference
    {
        get { return circumference; }
        set { circumference = value; }
    }

    public Shape()
    {
        this.area = 10;
        this.circumference = 200;
    }

    public abstract void compute(); // this method has no implementation

    public void display()
    {
       Console.WriteLine("Area Is : " + area + "\n" + "Circumference Is : " + circumference);
    }

}

Inheriting an abstract class:

public class Circle : Shape
{
     public override void compute() //have to give compute() method implementation
     {
          Console.WriteLine("Computing");
     }
}

If you don’t implement the compute() method then declare Circle as abstract

public abstract class Circle : Shape
{
      public void circleDisplay() { }
}


0 comments: