articles

Home / DeveloperSection / Articles / Abstract class in C#

Abstract class in C#

Anonymous User5664 05-May-2016

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
{
    publicabstractclassShapeAbstract
    {
        abstractpublic  int area();
    }
}

 

Square class

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

 

AbstractTest class

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

Output: Square : 144


Updated 27-Mar-2018
I am a content writter !

Leave Comment

Comments

Liked By