What is abstraction in C#?


Abstraction and encapsulation are related features in object-oriented programming. Abstraction allows making relevant information visible and encapsulation enables a programmer to implement the desired level of abstraction.

Abstraction can be achieved using abstract classes in C#. C# allows you to create abstract classes that are used to provide a partial class implementation of an interface. Implementation is completed when a derived class inherits from it. Abstract classes contain abstract methods, which are implemented by the derived class. The derived classes have more specialized functionality.

The following are some of the key points −

  • You cannot create an instance of an abstract class

  • You cannot declare an abstract method outside an abstract class

  • When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.

Example

 Live Demo

using System;
namespace Demo {
   abstract class Shape {
      public abstract int area();
   }

   class Rectangle: Shape {
      private int length;
      private int width;

      public Rectangle( int a = 0, int b = 0) {
         length = a;
         width = b;
      }
      public override int area () {
         Console.WriteLine("Rectangle class area :");
         return (width * length);
      }
   }
   class RectangleTester {
      static void Main(string[] args) {
         Rectangle r = new Rectangle(20, 15);
         double a = r.area();
         Console.WriteLine("Area: {0}",a);
         Console.ReadKey();
      }
   }
}

Output

Rectangle class area :
Area: 300

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 22-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements