25 Feb 2024
In C#, abstraction is achieved through several mechanisms:
-
Abstract Classes: These are classes that cannot be instantiated on their own and may contain abstract methods, which are methods without a body. Abstract classes can contain both abstract and non-abstract methods. Subclasses (classes that inherit from the abstract class) must implement all abstract methods, providing their own implementation details.
public abstract class Shape { public abstract double Area(); // Abstract method } public class Circle : Shape { public double Radius { get; set; } public override double Area() // Implementation of abstract method { return Math.PI * Radius * Radius; } } -
Interfaces: Interfaces define a contract that classes can implement. They consist of method signatures, properties, events, and indexers. Any class that implements an interface must provide implementations for all of its members.
public interface IShape { double Area(); // Method signature } public class Rectangle : IShape { public double Length { get; set; } public double Width { get; set; } public double Area() // Implementation of interface method { return Length * Width; } }
Abstraction allows you to define the structure and behavior of objects without specifying concrete implementations. This is useful for creating modular and extensible code, as it allows for the definition of common behavior among related classes while leaving the specific implementation details to the subclasses or implementing classes.