[C#] C# Abstraction and Interface

Date:     Updated:

Categories:

Tags:

📋 This is my note-taking from what I learned in the class “Programming 2”


Abstract

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.

  • In C#, an abstract class is a class that cannot be instantiated. Instead, it serves as a base class for other classes to inherit from. Abstract classes are used to define a common set of behaviors or properties that derived classes should have.
  • To create an abstract class in C#, you use the abstract keyword before the class definition.
// Create an abstract class
abstract class Language
{
  //fields and methods
}

// Try to create an object Language -> Throw an error
Language obj = new Language();


Abstract Class and Method

The abstract keyword is used for classes and methods:

  • Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
  • Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the derived class (inherited from).
    • An abstract method can only be present inside an abstract class.

An abstract class can have both abstract methods(method without body) and regular methods(method with body):

abstract class Animal
{
  // Abstract method(without body)
  public abstract void animalSound();

  // Non-abstract(regular) method(with body)
  public void sleep()
  {
    Console.WriteLine("Zzz");
  }
}

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

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

Example:

using System;

public abstract class Animal
{
  public abstract string Sound
  {
    get;
  }

  public virtual void Move()
  {
    Console.WriteLine("Moving");
  }
}

public class Cat : Animal
{
  public override string Sound => "Meow";

  public override void Move()
  {
    Console.WriteLine("Walking like a cat");
  }
}

public class Dog : Animal
{
  public override string Sound => "Woof";

  public override void Move()
  {
    Console.WriteLine("Walking like a dog");
  }
}

class Program
{
  static void Main (string[] args)
  {
    Animal[] animals = new Animal[] {new Cat(), new Dog()};

    foreach (Animal animal in animals)
    {
      Console.WriteLine($"The {animal.GetType().Name} goes {animal.Sound}");
      animal.Move();
    }
  }
}


Inheriting Abstract Class

To access the abstract class, it must be inherited from another class. Convert the Animal class using Polymorphism to an abstract class.

As we cannot create objects of an abstract class, we must create a derived class from it. So that we can access members of the abstract class using the object of the derived class.

Remember that we use the : symbol to inherit from a class, and that we use the override keyword to override the base class method.

// Abstract class
abstract class Animal
{
  // Abstract method(without body)
  public abstract void animalSound();

  // Regular method(with body)
  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
  }
}

When a non-abstract class inherits an abstract class, it should provide an implementation of the abstract methods.

abstract class Animal
{
  // Abstract method
  public abstract void makeSound();
}

// Inheriting from abstract class
class Dog : Animal
{
  // Provide implementation
  public override void makeSound()
  {
    Console.WriteLine("Bark");
  }
}

class Program
{
  static void Main (string[] args)
  {
    // Create an object of Dog class
    Dog obj = new Dog();
    obj.makeSound();
    Console.ReadLine();
  }
}

Why And When To Use Abstract Classes and Methods?

To achieve security - hide certain details and only show the important details of an object.


Sealed

Sealed

Sealed Class

In C#, when we don’t want a class to be inherited by another class, we can declare the class as a sealed class.

A sealed class cannot have a derived class. We use the sealed keyword to create a sealed class.

sealed class Animal
{
  // Code statement
}

// Trying to inherit sealed class, but occur error!
class Dog : Animal
{
  // Code statement
}

class Program
{
  static void Main (string[] args)
  {
    // Create an object of Dog class
    Dog d1 = new Dog();
    Console.ReadLine();
  }
}
  • In the above, created a sealed class Animal and tried to derive Dog class from the Animal class
  • Since a sealed class cannot be inherited, the program will generate the following error → error CS0509: ‘Dog’: cannot derive from sealed type ‘Animal’


Sealed Method

During method overriding, if we don’t want an overridden method to be further overridden by another class, we can declare it as a sealed method.

We use a sealed keyword with an overridden method to create a sealed method.

class Animal
{
  public virtual void makeSound()
  {
    Console.WriteLine("Animal Sound");
  }
}

class Dog : Animal
{
  // Sealed method
  sealed public override void makeSound()
  {
    Console.WriteLine("Dog Sound");
  }
}

class Puppy : Dog
{
  // Trying to override sealed method
  public override void makeSound()
  {
    Console.WriteLine("Puppy Sound");
  }
}

class Program
{
  static void Main (string[] args)
  {
    // Create an object of Puppy class
    Puppy d1 = new Puppy();
    Console.ReadLine();
  }
}
  • We have used the sealed keyword with makeSound(). → This means the Puppy class that inherits the Dog class is not allowed to override makeSound().
  • Hence, we get an error, when we try to override the makeSound() method inside Puppy class → error CS0239: ‘Puppy.makeSound()’: cannot override inherited member ‘Dog.makeSound()’ because it is sealed.
  • Sealing an overridden method prevents method overriding in multi-level inheritance.


Interfaces

In C#, an interface is similar to abstract class.

However, unlike abstract class, all methods of an interface are fully abstract(method without body).

We use the interface keyword to create an interface.

Interface Declaration

To declare an interface, use interface keyword. It is used to provide total abstraction. That means all the members in the interface are declared with the empty body and are public and abstract by default. A class that implements interface must implement all the methods declared in the interface.

// interface
interface IAnimal
{
  // Method without body
  void animalSound(); // interface method (does not have a body)
  void run(); // interface method (does not have a body)
}
  • It is considered good practice to start with the letter “I” at the beginning of an interface, as it makes it easier for yourself and others to remember that it is an interface and not a class.
  • By default, members of an interface are abstract and public.
  • Interfaces can contain properties and methods, but not fields.

Implementing Interface

To access the interface methods, the interface must be “implemented” (kinda like inherited) by another class. To implement an interface, use the : symbol (just like with inheritance). The body of the interface method is provided by the “implement” class. Note that you do not have to use the override keyword when implementing an interface:

// Interface
interface IAnimal
{
  void animalSound(); // interface method (does not have a body)
}

// Pig "implements" the IAnimal interface
class Pig : IAnimal
{
  public 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();
  }
}
  • In the above, we have created an interface named IAnimal
  • The interface contains a method animalSound() without implementation
  • The Pig class implements IAnimal and provides the implementation of the animalSound() method
  • Note: We must provide the implementation of all the methods of interface inside the class that implements it

Notes on Interfaces:

  • Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible to create an “IAnimal” object in the Program class).
  • Interface methods do not have a body - the body is provided by the “implement” class.
  • On implementation of an interface, you must override all of its methods.
  • Interfaces can contain properties and methods, but not fields/variables.
  • Interface members are by default abstract and public.
  • An interface cannot contain a constructor (as it cannot be used to create objects).

Why And When To Use Interfaces?

  • To achieve security - hide certain details and only show the important details of an object (interface).
  • C# does not support “multiple inheritance” (a class can only inherit from one base class). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma.


Multiple Interfaces

Unlike inheritance, a class can implement multiple interfaces.

To implement multiple interfaces, separate them with a comma:

interface IFirstInterface
{
  void myMethod(); // interface method
}

interface ISecondInterface
{
  void myOtherMethod(); // interface method
}

// Implement multiple interfaces
class DemoClass : IFirstInterface, ISecondInterface
{
  public void myMethod()
  {
    Console.WriteLine("Some text...");
  }
  public void myOtherMethod()
  {
    Console.WriteLine("Some other text...");
  }
}

class Program
{
  static void Main(string[] args)
  {
    DemoClass myObj = new DemoClass();

    myObj.myMethod();
    myObj.myOtherMethod();
  }
}




Back to Top

See other articles in Category CS

Leave a comment