Abstraction and Interfaces

Abstraction hides the details that do not matter so you can focus on what does. You will write abstract classes, define interfaces, and use them to write code that works with any class that keeps the contract.

Updated

General Abstraction

  1. Abstraction in Art (Novice): Abstraction means leaving out the details you don't need, shown through examples from art, math, language and the animal kingdom.

Abstraction in C#

  1. Abstraction in C#: an overview (Apprentice): In code, abstraction means working with an object through the few things that matter to you, and ignoring the rest. Base classes already do this; abstract classes and interfaces take it further.
  2. Inheritance Review (Apprentice): A quick look back at inheritance in C#. A derived class names its base class after a colon, inherits its members, adds its own, and overrides the base class's virtual methods.
  3. Adding Abstraction (Journeyman): Mark a base class abstract when it's too general to create on its own. An abstract class can't be created with new, and its abstract methods have no body, so every concrete derived class must override them.
  4. Summary (Journeyman): Abstraction is a goal; the abstract keyword is one C# tool for reaching it. Choose an ordinary, virtual or abstract method by whether derived classes keep, may change or must write it.

Interfaces in C#

  1. Interface Definition (Apprentice): The word "interface" is both a noun and a verb, and software uses both meanings.
  2. User Interfaces (Novice): A smart home's thermostat, wall panel, phone app and voice assistant show how many user interfaces can control the same software.
  3. Software Interfaces (Apprentice): A software interface is a contract between pieces of code. It lists what a class can do, never how, so code can use any class that keeps the contract. .NET is full of them, such as IEnumerable<T>.
  4. Solving Multiple Inheritance (Journeyman): A C# class can have only one base class, which avoids the confusion of inheriting two versions of the same method. Instead, it can implement as many interfaces as it needs, since an interface brings a contract, not code.
  5. Defining Interfaces (Journeyman): Define an interface with the interface keyword, a name starting with I, and members with no bodies. A class implements it by listing it after the colon, after its base class, and writing every member as public.
  6. Polymorphism with Interfaces (Freelancer): An interface can be a variable's, parameter's or list's type, so it can hold objects of unrelated classes that keep the same contract. Depending on an interface, such as IClock, lets a test pass any fake that implements it.

Exercise: Abstraction

  1. Exercise: Abstraction (Journeyman): Finish a city bike share. Make Vehicle an abstract class that every kind of vehicle prices for itself, give the electric ones the IChargeable contract, and write a RideService that gets its time from an IClock.