📦 Abstract Classes = Partial Implementation
Interfaces define contracts. Abstract classes provide partial implementation. Reuse code, enforce patterns.
📝 Abstract Class Example
public abstract class Animal
{
public string Name { get; set; }
// Abstract method (must be implemented)
public abstract void MakeSound();
// Virtual method (can be overridden)
public virtual void Eat()
{
Console.WriteLine($"{Name} is eating");
}
// Concrete method (shared)
public void Sleep()
{
Console.WriteLine($"{Name} is sleeping");
}
}
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Woof!");
}
public override void Eat()
{
base.Eat();
Console.WriteLine("Dog eats meat");
}
}
public class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("Meow!");
}
}
🎯 Real-World Use
// Base service public abstract class BaseService{ protected readonly IRepository _repository; protected readonly ILogger _logger; protected BaseService(IRepository repository, ILogger logger) { _repository = repository; _logger = logger; } public virtual async Task GetByIdAsync(int id) { _logger.LogInformation($"Getting {typeof(T).Name} {id}"); return await _repository.GetByIdAsync(id); } public abstract Task ValidateAsync(T entity); } public class UserService : BaseService { public UserService(IRepository repository, ILogger logger) : base(repository, logger) { } public override async Task ValidateAsync(User entity) { if (string.IsNullOrEmpty(entity.Email)) throw new ArgumentException("Email required"); } }
💡 Abstract vs Interface
- Abstract: Shared implementation, single inheritance
- Interface: Contract only, multiple inheritance
- Use abstract for base classes with common code
- Use interface for pluggable components
“3 services shared logging and validation. Abstract base class reduced duplication. Cleaner, maintainable.”
