C# Abstraction

Abstraction is a mechanism by which we can hide the complexities and show only functionalities. C# provides an abstract keyword to declare a class and method as abstract. In C#, Abstraction is achieved by two ways:

  1. By abstract class
  2. By Interface
Abstract class and interface both can have abstract methods which are necessary to achieve abstraction.
  1. Abstract Methods:
A Method which has only declaration and no definition is called Abstract Method. An abstract method can only be declared inside abstract class. It must be overridden else there is no meaning of declaring abstract method. Syntax:
abstract <return type> <method name>(<parameter list>);
An abstract method can’t be sealed. We can’t declare it as static. It’s internally a virtual method.
  1. Abstract Class:
Abstract class is the class which can have abstract and non abstract methods inside it. Abstract class is used to define a blueprint of a derived class. It can’t be instantiated. This needs to be derived if you want to use its properties. We have to give implementation of all the abstract methods of abstract class. If you are deriving an abstract class into your class then you must override all the abstract methods present in that class or declare your class as abstract. Let's see an example of Abstract class.
using System;
public abstract class Shape
{
                        public abstract void draw();
}
public class Triangle:Shape
{
                        public override void draw()
                        {
                                    Console.WriteLine("drawing traingles...");
                        }
}
public class TestAbstractClass
{
                        public static void Main (string[] args)
                        {
                                    Shape s=new Triangle();
                                    s.draw();
                        }
}
Output
drawing traingles...
C# abstract class example: having Constructors and methods in abstract class
 using System;
public abstract class Car
{
                        public Car()
                        {
                                    Console.WriteLine("Car is created");
                        }
            public abstract void show();
            public void speed()
            {
                        Console.WriteLine("speading...");
            }
}
public class Hundai:Car
{
                        public override void show()
                        {
                                    Console.WriteLine("showing brand new Hyundai i20....");
                        }
}
public class AbstractClassExample
{
public static void Main (string[] args)
{
                                    Hundai h=new Hundai();
                                    h.show();
                                    h.speed();
}
}
Output
Car is created
showing brand new Hyundai i20....
speading...