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:
- By abstract class
- By Interface
- Abstract Methods:
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.
- 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...