Abstract Class in C#


Abstract Class:
  1. An abstract class cannot be instantiated.
  2. An abstract class may contain abstract methods and also contain own concrete method.
  3. We want use the abstract class must be inherited by the non abstract class.
  4. A non-abstract class, which derived from an abstract class must include implementations for all inherited abstract methods
  5. An abstract method is implicitly a virtual method.
  6. In abstract method declaration provides no actual implementation, there is no method body; it has only the signature
  7. The implementation is provided by an overriding method (using override keyword in c#), which is a work as a member of non-abstract class.
Code:

    public
abstract class ClassBase //abstract classes
    {
        //Abstract class constructor
        public ClassBase()
        {
            Console.WriteLine("Abstract Constructor");
        }

        //Own completed method in Abstract Class
        public void useinsub() 
        {
            Console.WriteLine("Call by sub-class/non abstract");
        }

        //Virtual method in abstract class
        public virtual void fill() 
        {
            Console.WriteLine("Abstract Virtual Function");
        }

        //Pure abstract method
        public abstract void fill2();
    }

    public class ClassSub : ClassBase //Sub Class(Non Abstarct)
    {
        // Sub class constructor
        public ClassSub()
        {
            Console.WriteLine("Sub Constructor");
        }

        // Over ride the virtual method in abstract class
        public override void fill()
        {
            Console.WriteLine("Override the virtual Function");
        }

        // Implement the abstract method, which is in abstract class
        public override void fill2()
        {
            Console.WriteLine("Implement the abstract Function");
            //Call abstract class's own completed method
            base.useinsub();
        }        
    }
    class Program
    {
        static void Main(string[] args)
        {
            ClassSub cs = new ClassSub();
            cs.fill();
            cs.fill2();
        }
    }
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now