English
Summary
Conclusions
Abstract classes and interfaces express abstraction: what types must be able to do, without defining the implementation. An abstract class cannot be instantiated; it contains abstract members that derived classes implement, as well as shared code, state, and constructors, which makes it the basis of the template method. An interface is a contract without state: a class can implement several interfaces, members with the same signature are implemented explicitly, and default members and static abstract members extend what interfaces can do. Standard .NET interfaces integrate your own classes with the library: IComparable<T> and IComparer<T> for sorting, IEquatable<T> for equality, and IDisposable with using for releasing resources. Programming to interfaces provides loose coupling and swappable implementations.
Self-check questions
- What is abstraction in OOP?
- What is an abstract class? How does an abstract method differ from a virtual one?
- Can an abstract class have a constructor and fields?
- What is the template method? Give an example.
- What is an interface? What members can it contain?
- How do you implement several interfaces in one class?
- How do you check whether an object implements an interface?
- What is explicit interface implementation? When is it needed?
- What are default interface members?
- What are static abstract interface members for?
- How do
IComparable<T>andIComparer<T>differ? - What is
IDisposablefor? How does theusingstatement work? - How does an abstract class differ from an interface? When do you choose which?
- What does programming to interfaces mean?
- How are abstract classes and interface implementation shown in UML diagrams?
Useful links
- The
abstractkeyword: https://learn.microsoft.com/dotnet/csharp/language-reference/keywords/abstract - Interfaces: https://learn.microsoft.com/dotnet/csharp/fundamentals/types/interfaces
- Explicit interface implementation: https://learn.microsoft.com/dotnet/csharp/programming-guide/interfaces/explicit-interface-implementation
IComparable<T>: https://learn.microsoft.com/dotnet/api/system.icomparable-1- Implementing
Dispose: https://learn.microsoft.com/dotnet/standard/garbage-collection/implementing-dispose