Wednesday, 4 December 2019

Abstract class in c#

An abstract class in an incomplete class or special class and we can't be instantiated. The purpose of abstract class is to provide a blueprint for derived classes and set some rules what the derived classes must implement when they inherit an abstract class.
1. Cannot create an instance of abstract class
2. If a class is an abstract class then it can contain abstract methods and non-abstract methods.
3. If we declare method as a abstract in base class (abstract class) then it is mandatory for all derived class to implement abstract methods.

Abstract Class Contains:
--Abstract Methods
--Non-abstract Methods

Code Example:-

public abstract class AbstractClassExample
    {
        public abstract void add(int a, int b); //abstract method
        public abstract void sub(int a, int b); //abstract method

        public int div(int a, int b) //non-abstract method of parent class
        {
            return a / b;
        }
    }

 
    class ChildClass : AbstractClassExample
    {
        public override void add(int a, int b)  //mandatory to implement
        {
            Console.WriteLine("Addition:" + (a + b));
        }
        public override void sub(int a, int b)  //mandatory to implement
        {
            Console.WriteLine("Substraction:" + (a - b));
        }

        public void mul(int a, int b)   //method of child class
        {
            Console.WriteLine("Multiplication:" + (a * b));
        }
        static void Main(string[] args)
        {
            //AbstractClassExample abc = new AbstractClassExample(); //cannot create the instance of abstract class

            ChildClass c = new ChildClass();
            c.add(10, 20);
            c.sub(20, 10);
            Console.WriteLine("Division:" + c.div(20, 4));
            c.mul(10, 5);
            Console.ReadLine();
        }
    }


Output:



No comments:

Post a Comment