What are interfaces and abstract classes

Interfaces and abstract classes are both important concepts in object-oriented programming in C#. They provide a way to define contracts and base functionality which can be implemented or inherited by derived classes.

Interfaces

An interface is a contract that defines a set of methods and properties without implementing them. Any class that implements an interface must provide an implementation for all its members. Interfaces allow for polymorphism and multiple inheritance in C#.

Abstract Classes

An abstract class is a class that cannot be instantiated on its own and may contain abstract methods (without implementation) as well as concrete methods (with implementation). Abstract classes allow for shared functionality while enabling derived classes to implement their unique behavior.

Example:

// Define an interface public interface IVehicle { void Start(); void Stop(); } // Define an abstract class public abstract class VehicleBase { public abstract void Move(); public void Refuel() { Console.WriteLine("Refueling..."); } } // Implementing the interface and inheriting from the abstract class public class Car : VehicleBase, IVehicle { public override void Move() { Console.WriteLine("Car is moving..."); } public void Start() { Console.WriteLine("Car started."); } public void Stop() { Console.WriteLine("Car stopped."); } }

interfaces abstract classes C# object-oriented programming polymorphism inheritance