DEV Community

Cover image for Principles Of Object-Oriented Programming Part 2- Encapsulation
Elegberun Olugbenga
Elegberun Olugbenga

Posted on • Updated on

Principles Of Object-Oriented Programming Part 2- Encapsulation

Welcome to part 2 on or series of the Principles of Object-Oriented Programming in c#. If you have not read part 1 you can check it out here.

In this article we will be talking about Encapsulation.

Encapsulation

If you google the definition of the word encapsulation you will see this(the action of enclosing something in or as if in a capsule). If we relate it to programming this just means binding all the data and logic in a single unit called a class. Encapsulation in C# is implemented with different levels of access to object data that can be specified using access modifiers.This means that different parts of the application can either be displayed or hidden depending on the level of access given. An example would be you as an employee choosing to show parts of your life to the public like Name,Employee ID, and then hiding other parts of your life like age and salary choosing to show that to select people. But all these methods and properties are encapsulated in you as a person and you just choose which side to show the world using access modifiers.
Encapsulation

Encapsulation-image from tamiltechportal.com

Access Modifiers

Access Modifiers are a key component of C# and object-oriented programming. They specify the accessibility of all objects and their members and determine the level of visibility of classes, methods and properties.They help ensure the privacy of our entities.

Types of Access Modifiers

Private:

This means that the entity is only accessible within that class and cannot be accessible outside it. An example is if you want to create an app and in your registration module you made a method to encrypt password and that method should only be only be accessible within your registration class so you make the method private. Access Modifiers can be applied to variables and methods

Example:

public class Registration 
{
      private bool isPasswordHashed = false;

  Private string CreatePasswordHash()
  {
////logic for hashing password 
    isPasswordHashed= true;
  return "HashedPasword";
  }
}
Enter fullscreen mode Exit fullscreen mode

If you try to use the private variable or method in another class you will get this error.

public class Registration2 
{
public string GetHashedPassword(string password))
 {
  Registration registration= new Registration();
   string hashedPassword= registration.CreatePasswordHash();/////Error this method is inaccessible due to its protection Level.
 ////Or if you try to access the variable.
   bool isPasswordHashed =registration. isPasswordHashed;/////Error this variable is inaccessible due to its protection Level.

  return "Hashed Password";
 }
}
Enter fullscreen mode Exit fullscreen mode

Public:

This means that our properties are accessible everywhere within the class and outside it. If you created logic to send email to the customer after they have successfully performed an action and you wanted this send email method to be accessible everywhere in your application even outside your class. You can make it public.

Example:

public class Registration
{
  Public void  SendEmail()
  {
    ////logic for sending Email
   }
} 
public class Registration2 
{
public string SendEmailtoCustomer()
 {
   Registration registration= new Registration();
   registration.SendEmail();/////this method is Accesible because it is public ;

 return "Email Sent Successfully";
 }

}
Enter fullscreen mode Exit fullscreen mode

Protected:

This means that the property is accessible within its class and any class that is derived from this class. It is accessible but the class that wants to use it has to derive from it to use its properties and methods. Let's make the sendEmail method protected and try what we did before

Example:

public class Registration
{
  protected  void SendEmail()
  {
    ////logic for sending Email
   }
} 

public class Registration2 
{
  public string SendEmailtoCustomer()
  {
    Registration registration= new Registration();
   registration.SendEmail();/////Error this method is 
   inaccessible due to its protection level

   return "Email Sent Successfully";
  }
}
Enter fullscreen mode Exit fullscreen mode

But if we derive from the Registration Class it becomes accessible.

public class Registration2:Registration /////deriving from Registration class
{
  public string SendEmailtoCustomer()
 {
    Registration registration= new Registration();
   registration.SendEmail();/////this method is accessible 
  because its class has derived from the base class 
  (Registration)

  return "Email Sent Successfully";
 }
}
Enter fullscreen mode Exit fullscreen mode

Internal:

This keyword means that the property is only accessible within an assembly. An assembly is a file that is automatically generated by the compiler upon successful compilation of every.NET project. It is the reference to the application itself. The keyword (internal) means that the property is only accessible within this specific assembly. If I give you my applications assembly and you try to access any property that is internal you wont be able to access it.

Example:

/////Assembly one
public class Registration
{
 internal void SendEmail()
  {
    ////logic for sending Email
   }
} 

/////Assembly two
public class Registration2 
{
public string SendEmailtoCustomer()
 {
    Registration registration= new Registration();
   registration.SendEmail();/////Error this method is inaccessible due to its protection level.
                               ///The Program class in second project can't access the internal members from another project

 return "Email Sent Successfully";
 }
}
Enter fullscreen mode Exit fullscreen mode

Protected Internal:

This means the property can be either Protected OR internal. Lets look at the example below. Here are two assemblies. Normally Because of the (internal) keyword we would have not been able to access this in another assembly but because it satisfies the conditions of the (Protected) as explained above it can be accessed. It has to satisfy one of the conditions.(Protected OR Internal).

Example:

/////Assembly one
public class Registration
{
  protected internal void SendEmail()
  {
    ////logic for sending Email
   }
} 

/////Assembly two
public class Registration2 : Registration
{
public string SendEmailtoCustomer()
 {
    Registration registration= new Registration();
   registration.SendEmail();///// Normally this would have been inaccessible because of the (internal keyword)but because it satisfies the condition of the (protected keyword) it is accessible.

 return "Email Sent Successfully";
 }
}
Enter fullscreen mode Exit fullscreen mode

If i am being honest I have not really found a good use case of this.

Private Protected:

This is a combination of both private and protected. This means the property is private AND protected. It can be accessible to derived classes because of the(protected) keyword but only within the assembly because of the (private keyword). So it has to satisfy both of the conditions.(Private AND Protected).

Example:

/////Assembly one
public class Registration
{
  private protected void SendEmail()
  {
    ////logic for sending Email
   }
} 
public class Registration2:Registration
{
public string SendEmailtoCustomer()
 {
    Registration registration= new Registration();
   registration.SendEmail();///// accessible because it satisfies the condition of protected keyword

 return "Email Sent Successfully";
 }
}

/////Assembly Two
public class Registration2 : Registration
{
public string SendEmailtoCustomer()
 {
    Registration registration= new Registration();
   registration.SendEmail();///// inaccessible because it does not satisfy the private keyword condition.(it is in a different assembly)

 return "Email Sent Successfully";
 }
}
Enter fullscreen mode Exit fullscreen mode

STATIC KEYWORD

The static keyword makes an item non-instantiable. It can be applied to classes, variables and methods. If a static keyword is applied to a variable, method or class then it can not be instantiated which means you cannot create an object of it. You are always going to be referring to the concrete implementation. If it is applied to classes all methods inside that class must be static too.

public static class Registration
{
    public static void sendEmail()
    {
       // logic for sending email.
    }
}

public  class Registration2
{
  public string SendEmailtoCustomer()
 {
   Registration registration= new Registration();///this will give an error cannot create an instance of a static class Registration

Registration.sendEmail()....this will work because you are using the class name itself.

 return "Email Sent Successfully";
 }
}
Enter fullscreen mode Exit fullscreen mode

To better understand how modifiers work take a look at the figure below.
Alt Text

Access Modifier Table Summary

There are still some other keywords and access modifiers you will come across when coding in Object-oriented programming but hopefully, these can get you started.

In Summary

Encapsulation is binding the data and logic of an application into a single unit.

We can show or hide which methods or variables we want by using access modifiers.

Check out part 3 about Abstraction

here

Top comments (0)