Home > DeveloperSection > Articles > Abstract class in C#

Abstract class in C#


C# C#  OOPS  Abstract Class 
Ratings:
0 Comment(s)
 625  View(s)
Rate this:

Abstract class in C#



A Method without any method body is known as an abstract, what the method contain only declaration without any implementation & should be declare by only the ‘abstract modifier’.

The class under which we define these abstract methods is an abstract class & should be declared by ‘abstract modifier’.


The purpose of abstract class is to provide default functionality to its sub classes:

1. When a method is declared as abstract in the base class then every derived class of that class must provide its own definition for that method.

2. An abstract class can also contain methods with complete implementation, besides abstract methods. 

3. When a class contains at least one abstract method, then the class must be declared as abstract class. 

4. It is mandatory to override abstract method in the derived class. 

5. When a class is declared as abstract class, then it is not possible to create an instance for that class. But it can be used as a parameter in a method.

 

Example:


ShapeAbstract class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace OopsConcepts
{
    public abstract class ShapeAbstract
    {
        abstract public  int area();
    }
}

 

Square class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace OopsConcepts
{
    class Square:ShapeAbstract
    {
        int side = 0;
        public Square(int n)
        {
            side = n;
        } 
        public override int area()
        {
            return side * side;
        } 
    }
}

 

AbstractTest class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace OopsConcepts
{
    class AbstractTest
    {
        static void Main(string[]args)
        {
          Square sq = new Square(12); 
           Console.WriteLine("Square : {0}", sq.area());
      }
   }

Output: Square : 144


Don't want to miss updates? Please click the below button!

Follow MindStick