Abstract class in c#
2 min readFeb 8, 2024
- In c#,
Abstract class
is a class that can not be instantiated on its own - It is typically used as a
base class
for other class. Abstract class
provides a way to achieve abstraction, because there you can just declare the methods (abstract methods) and implement them later.- It can contain both
abstract methods
(methods without implementation details) andnon-abstract methods
(method with implementation details). - Similar goal can be achieved with
interface
, but in abstract class you can also define non-abstract method. These methods are needed when you need to share some common functionality.
public abstract class Shape
{
// it is the basic syntax of abstract class
}
Example:
abstract class Shape
{
public abstract void Draw(); // Abstract method without implementation
public void Display() //non abstract method
{
Console.WriteLine("Displaying shape...");
}
}
// concrete class
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle");
}
}
// concrete class
class Square : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a square");
}
}
class Program
{
static void Main()
{
Shape circle = new Circle();
circle.Draw(); // Drawing a circle
circle.Display(); //Displaying shape...
Shape square = new Square();
square.Draw(); // Drawing a square
square.Display(); //Displaying shape...
}
}
- Shape is an abstract class, which contains an
abstract method
Draw() andnon-abstrac
t method Display(). - We are defining high level overview of any shape. Whatever shape we will have, it must have a feature
Draw
. Since we don’t know the details of the shape yet (it may be circle, pentagon, rectangle) , we can not define it it advance. Circle/Rectangle/Pentagon will have it’s owndraw
method. That’s whyDraw()
method is marked asabstract-method
. It’s implementation will be defined later. - Now we have two class
Circle
andSquare.
Each class will inherit theShape
class and override theDraw()
method.
If you find this article useful, then consider to clap 👏 and share it. You can also follow me on YouTube, I have created lots of content related to .net core and angular.
Connect with me
👉 YouTube: https://youtube.com/@ravindradevrani
👉 Twitter: https://twitter.com/ravi_devrani
👉 GitHub: https://github.com/rd003
Become a supporter ❣️:
You can buy me a coffee 🍵 : https://www.buymeacoffee.com/ravindradevrani
Thanks a lot 🙂🙂