C# Abstraction

C# Abstraction

Data abstraction is the process of hiding certain details and showing only essential information to the user.

Abstraction can be achieved with either abstract classes or interfaces (which we will learn more about in the next chapter).


Abstract Classes and Methods

The abstract keyword is used for classes and methods:

Let's look at why we might need this.

If you have a base class Animal, it makes sense to have objects of Dog and Pig. But does it make sense to create a generic Animal object? What sound does a generic "Animal" make? It doesn't.

We can mark Animal as abstract so no one can create a raw Animal object.

Example: Abstract Class and Method

using System;

// Abstract class abstract class Animal { // Abstract method (does not have a body) public abstract void AnimalSound();

// Regular method public void Sleep() { Console.WriteLine("Zzz"); } }

// Derived class (inherit from Animal) class Pig : Animal { // We MUST provide the body for the abstract method here public override void AnimalSound() { Console.WriteLine("The pig says: wee wee"); } }

class Program { static void Main(string[] args) { // ERROR: Cannot create an instance of the abstract class // Animal myObj = new Animal(); Pig myPig = new Pig(); // Create a Pig object myPig.AnimalSound();
myPig.Sleep();
} }

Key Rules of Abstraction:

  1. You cannot use the new keyword to create an object of an abstract class.
  2. An abstract class can contain both abstract methods and regular methods.
  3. If a child class inherits an abstract class, it must provide implementations (override) for all of the abstract methods.

Exercise

?

Can you create an object directly from an abstract class?