In c#, Abstract class is a class that can not be instantiated on its own
- 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 achieveabstraction
, 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 anabstract class
, which contains anabstract method
Draw()
andnon-abstract
methodDisplay()
.- 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.
Originally posted by Ravindra Devrani on February 8, 2024.
Exported from Medium on February 19, 2025.