Web Design that taps into the haromny and vision of your dreams.

C# Class Abstraction and Encapsulation

What are abstract classes and encapsulation?

Written By on in C#

483 words, estimated reading time 3 minutes.

Abstract classes provide a way to force an inherited class to implement an override method, similar to, but not the same as an interface. Encapsulation is the ability for an object to hide its data and methods from those who do not need to know, and only expose data and methods that are required.

Advanced C# Programming Series
  1. C# Advanced Data Types
  2. Using C# Properties and Indexers
  3. C# Event Handling and Delegates
  4. Method Overloading and Overriding in C#
  5. C# Class Abstraction and Encapsulation
  6. C# Aggregation and Advanced Scope Techniques
  7. Polymorphism in C#
  8. Boxing and Unboxing Value Types in C#
  9. C# Operator Overloading
  10. Creating Multi-Threading Applications with C#
  11. Unsafe Code Execution in Microsoft .Net

Abstraction

Unlike an interface, abstract classes are fully functional classes, but you can force one or more methods to be overridden.

Let's say you had a theoretical vehicle class. Every vehicle must be able to steer (i.e. must have a steer() method) however different types of vehicle will have different implementation of this method. It is pointless to implement this method in the base class as the code will not be used and could not possibly contain enough information for the derived class to use. It is also dangerous to leave it empty as it could be called without any implementation causing the resulting vehicle to be unable to steer! By marking the method as abstract, you force any derived classes to have their own specialised implementation of the method.

Both the class and the method must be marked as abstract. Because there is no implementation of the steer method, the statement is terminated with a semi-colon.

public abstract class Vehicle
{
  public abstract void steer();
}

Now, each class that inherits from the Vehicle class must implement the steer method.

public class Car : Vehicle
{
  public override void steer()
  {
    // Implement a steering wheel
  }
}
 
public class Bike : Vehicle
{
  public override void steer()
  {
    // Implement handlebars
  }
}
 
public class Tank : Vehicle
{
  public override void steer()
  {
    // Implement tracked drive steering
  }
}
 
public class Airplane : Vehicle
{
  public override void steer()
  {
    // Implement ailerons and rudders
  }
}

This ensures that all inherited classes always have a specific implementation of the abstract method.

Encapsulation

Encapsulation is the ability for an object to hide its data and methods from those who do not need to know, and only expose data and methods that are required.

Techniques for encapsulation include class abstraction and properties. Sometimes you may not wish direct interaction with an object's data field, for example in a bank account class you would not want to expose a balance field where it could possibly be modified without any checks or security.

Encapsulation is the process of protecting the data using properties, so that any attempt to modify the data is done through the proper channels, ideally with an audit log for the bank account class.

Using the rather cliche BankAccount class as an example, we can encapsulate the account balance to prevent invalid or unwanted access. Yes, I know that this is not how a bank account should function, but it serves for the purpose of this example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication2
{
    class BankAccount1
    {
        public decimal Balance;
    }
 
    class BankAccount2
    {
        private decimal _balance;
        public decimal Balance
        {
            get 
            { 
                return _balance; 
            }
 
            set 
            { 
                // do security checks and validation
                if (value > 0)
                    _balance = value;
                else
                    throw new InvalidOperationException();
            }
        }
    }
 
 
    class Program
    {
        static void Main()
        {
            BankAccount1 ba1 = new BankAccount1();
            ba1.Balance = -100; // Dangerous as this is allowed
 
            BankAccount2 ba2 = new BankAccount2();
            ba2.Balance = -100; // This is now not allowed and raises an error
        }
    }
}

Last updated on: Friday 23rd June 2017

 

Comments
Manish

Manish

Abstraction is different thing you have explained abstract class over here in the comparison of encapsulation.
You should have to explain Abstraction process not abstract class and its features.

Reply to Manish
g

g

gud article

Reply to g
Priya Arora

Priya Arora

can u plz help to find out the difference between abstraction & encapsulation. We know that encapsulation is hiding the unnecessary data & abstraction is showing the necessary data but wats the difference in this both are performing the same task.

Reply to Priya Arora
Tim Trott

Tim Trott

NickyBics, Yes they should! Thanks for pointing that one out. Page updated.

Reply to Tim Trott
NickyBics

NickyBics

Shouldn't the definitions:
public class Car : Bike
public class Car : Tank
public class Car : Airplane

actually be:
public class Bike : Vehicle
public class Tank : Vehicle
public class Airplane : Vehicle

?

Reply to NickyBics

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me