Home > DeveloperSection > Blogs > Abstraction

Abstraction


C# C# 
Ratings:
0 Comment(s)
 2010  View(s)
Rate this:

Abstraction 

Abstraction is used to create a common set of methods that might have different specific implementations by subclasses. Abstract class cannot be instantiated and consists of abstract methods without any implementations. Classes inheriting from abstract class must implement all the methods in abstract class. An abstract class is a parent class that allows inheritance but can never be instantiated. Abstract classes contain one or more abstract methods that do not have implementation.

Example:-

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Abstraction

{

publicabstract classTalk //Abstract Class

{

// An abstract method is a method without any method body.

public abstract void Speak();// Abstract Method( only declaration with empty body)

}

publicclass sayMorning : Talk // Inheriting the Abstract Class

{

public override void Speak() // Overrinding the Abstract Method (Defining the base class Abstract Method)

{

Console.WriteLine("Good Morning"+ "\n");

}

}

publicclass sayAfterNoon : Talk

{

public override void Speak()

{

Console.WriteLine("Good Afternoon" + "\n");

}

}

publicclass sayNight : Talk

{

public override void Speak()

{

Console.WriteLine("Good Night" + "\n");

}

}

classProgram

{

static void Main(string[] args) //The main entry point for the application.

{

// Talk objTalk = new Talk(); // It will Generate and error because Abstract Class can'b be instantiated

sayMorning objSayMorning = new sayMorning(); //Creating Object

sayAfterNoon objSayAfternoon = new sayAfterNoon();

sayNight objSayNight = newsayNight();

objSayMorning.Speak();

objSayAfternoon.Speak();

objSayNight.Speak();

}

}

}

Output:-

Good Morning

Good Afternoon

Good Night

In the above Program, I have created an Abstract Base Class named Talk, Which contain an Abstract Method Speak () with declaration only (abstract methods are further defined in Sub Class of Abstract Base Class and must be overridden by Sub Class).

This Program also contains three more classes named sayMorning, sayAfterNoon, sayNight. All these three classes are inheriting the Abstract Base Class names Talk and overriding the abstract method using override keyword (Implementation logic of Abstract Methods are provided by class that derive from them).


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

Follow MindStick