C# Abstract Class & Methods
In C#, an abstract class is a class that cannot be instantiated, i.e., you cannot create an object of an abstract class. An abstract class is used as a base class to provide a common interface for a set of derived classes. It can contain both abstract and non-abstract methods.
An abstract method is a method that has no implementation in the abstract class. The implementation is provided by the derived classes that inherit from the abstract class. To declare an abstract method, you use the abstract
keyword. An abstract method has no body and ends with a semicolon.
Here's an example of an abstract class and an abstract method:
refer to:theitroad.comabstract class Shape { public abstract double Area(); } class Rectangle : Shape { private double length; private double width; public Rectangle(double length, double width) { this.length = length; this.width = width; } public override double Area() { return length * width; } } class Circle : Shape { private double radius; public Circle(double radius) { this.radius = radius; } public override double Area() { return Math.PI * radius * radius; } }
In this example, we define an abstract class called Shape
. The Shape
class has one abstract method, Area()
, which returns the area of the shape. The Rectangle
and Circle
classes inherit from the Shape
class and provide their own implementation of the Area()
method.
The Rectangle
class calculates the area of a rectangle using its length and width, while the Circle
class calculates the area of a circle using its radius.
You cannot create an object of the Shape
class, but you can create objects of the derived classes, such as Rectangle
and Circle
. Here's an example:
Rectangle rect = new Rectangle(5, 10); Circle circle = new Circle(3); Console.WriteLine("Rectangle area: " + rect.Area()); Console.WriteLine("Circle area: " + circle.Area());
In this example, we create a Rectangle
object with a length of 5 and a width of 10, and a Circle
object with a radius of 3. We then call the Area()
method on each object to get their areas.