ARTICLE

Abstract Classes in C#

Posted by Mayur Gujrathi Articles | Visual C# April 21, 2011
When a method is declared as abstract it is mandatory for the child class to implement it, without which it can't use other members and methods of the parent class.
Reader Level:


We know that when method declared as virtual can be implemented in child class by creating object of parent class but it is optional when we declare it as Virtual. But in some case there might be requirement that child class must and should implement particular method, in this case it should be declare as Abstract. When method is declared as abstract it is mandatory for child class to implement it, without which it can't use other members and methods of the parent class. First it must implement the abstract method in the parent class as there can be a method body not implemented for an abstract class in a parent class.

Some more points for Abstract classes

  • An abstract method is implicitly a virtual method.
  • Abstract method declarations are only permitted in abstract classes.
  • Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ })

 Following the signature. For example:

using System;
namespace
OOPSProject
{
    abstract class AbsParent
    {
        public void Add(int x, int y)
        {
            Console.WriteLine(x + y);
        }
        public void Sub(int x, int y)
        {
            Console.WriteLine(x - y);
        }
        public abstract void Mul(int x, int y);//only method declaration
        public abstract void Div(int x, int y);//only method declaration
    }
}
 
using System;
namespace OOPSProject
{
    class AbsChild : AbsParent
    {
    //first we have to implement abstract methods of parent class
        public override void Mul(int x, int y)
        {
            Console.WriteLine(x * y);
        }
        public override void Div(int x, int y)
        {
            Console.WriteLine(x / y);
        }
        static void Main()
        {
            AbsChild c = new AbsChild();
            AbsParent p = c;           
            p.Add(100, 50); p.Sub(156, 78);//then we can invoke other methods
            p.Mul(50, 30); p.Div(625, 25);
            Console.ReadLine();
        }
    }
}

Login to add your contents and source code to this article
post comment
     
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Get Career Advice from Experts