Abstract classes

When we declare a class to be abstract, it is not possible to declare an object of the class. However, we can define a function in an abstract class (which makes it different from interface).

We can also provide the signatures of methods and properties in abstract class, that must have “abstract” keyword in their signature. All such methods and properties (declared as abstract) must be “overridden” in the classes derived from abstract class

Here is an example, in which we have one abstract method, one abstract property, and one non abstract method defined in abstract class:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;


namespace ConsoleApplication6
{
    abstract class MyClass
    {
        public abstract int sum();

        public abstract double Area
        {
            set;
            get;
        }

        public void MyMethod()
        {
            Console.WriteLine("This is abstract class function");
        }
    }
    class DerivedClass : MyClass
    {
    double area, length, width;
        
        public override double Area
        {
            set
            {
                area = value;
            }
            get
            {
                return area;
            }
        }

        public double Length
        {
            set {
                length = value;
            }

            get
            {
                return length;
            }
        }


        public double Width
        {
            set
            {
                width = value;
            }

            get
            {
                return width;
            }
        }



        public override int sum()
        {
            return 2 + 2;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            DerivedClass d = new DerivedClass();
            d.Length = 10;
            d.Width = 20;
            d.Area = d.Length * d.Width;

            Console.WriteLine(d.Area);
            Console.WriteLine(d.sum());

        }   
    }
}

 

 

Tags:,

Add a Comment

Your email address will not be published. Required fields are marked *