C# Abstraction


Abstract Classes and Methods

Data abstraction is the process of hiding certain information and displaying only important information to the user.

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

Abstract keyword is used for classes and methods:

  • Abstract category: is a limited category that can be used to create things (to achieve that, you must achieve another category).
  • Abstract method: can only be used in the invisible class, and it has no body. The body is provided by a derived (inherited) category.

An abstract class can have both abstract and regular methods:

abstract class Animal 
            {
              public abstract void animalSound();
              public void sleep() 
              {
                Console.WriteLine("Zzz");
              }
            }
            

From the example above, it is not possible to create an Animal class object:

Animal myObj = new Animal(); // Will generate an error (Cannot create an instance of the abstract class or interface 'Animal')
        

To access an abstract class, it must be inherited from another class. Let's convert the Animal category we used in the Polymorphism chapter into an abstract class.

Example
// 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
            {
              public override void animalSound()
              {
                // The body of animalSound() is provided here
                Console.WriteLine("The pig says: wee wee");
              }
            }
            
            class Program
            {
              static void Main(string[] args)
              {
                Pig myPig = new Pig(); // Create a Pig object
                myPig.animalSound();  // Call the abstract method
                myPig.sleep();  // Call the regular method
              }
            }