Abstract Class and Abstract Method in C#


 In C#, an abstract class is a class that cannot be instantiated on its own and is typically used as a base class for other classes. It may contain a mix of concrete (implemented) methods and abstract (unimplemented) methods. Abstract methods are declared within an abstract class but do not have any implementation. These methods are meant to be overridden by derived classes to provide specific implementations. Here's how abstract classes and abstract methods work in C#:

Abstract Class:

To define an abstract class, you use the abstract keyword in the class declaration. Abstract classes can include fields, properties, and methods, some of which can be abstract. An abstract class can also include fully implemented methods (concrete methods).

public abstract class Shape { public string Color { get; set; } // Abstract method without implementation public abstract double CalculateArea(); // Concrete method public void SetColor(string color) { Color = color; } }

In this example, Shape is an abstract class that contains an abstract method CalculateArea() and a concrete method SetColor().

Abstract Method:

An abstract method is a method that is declared without any implementation in an abstract class. It is marked with the abstract keyword, and its purpose is to provide a contract that derived classes must fulfill by implementing the method.

public abstract class Shape { // Abstract method without implementation public abstract double CalculateArea(); }

Derived classes that inherit from an abstract class must provide an implementation for all the abstract methods in the base class. For example:

public class Circle : Shape { public double Radius { get; set; } public Circle(double radius) { Radius = radius; } public override double CalculateArea() { return Math.PI * Radius * Radius; } }

In this example, the Circle class derives from the Shape abstract class and provides an implementation for the CalculateArea() method, as required.

Key points about abstract classes and abstract methods:

  1. Abstract classes cannot be instantiated. You can only create instances of derived (concrete) classes.

  2. Abstract methods must be implemented by any concrete class that inherits from the abstract class.

  3. Abstract classes can include concrete methods, properties, and fields in addition to abstract methods.

  4. Abstract classes provide a level of common functionality and structure for derived classes while ensuring that certain methods are implemented consistently across derived classes.

  5. Abstract methods define a contract that derived classes must adhere to, promoting a level of consistency and predictability in class hierarchies.

Abstract classes and methods are essential tools for building object-oriented systems in C# when you want to create a common base structure while enforcing specific behaviors in derived classes.

Post a Comment

Previous Post Next Post