Article

Encapsulation


Encapsulation

Encapsulation is used to protect the data from being accessed by outside.It is a process that binds together code and data which is manipulates according to requirement. Encapsulation means that covering up of data under a single unit.

  • For Using data where we declare variables as private. By following ways we use data without any damage or change.
  • For using the data in the class.we declare mutator(set method) and accessor(get method).
  • Encapsulation also used by properties.By using set accessor in the property implementation for accomplished write-only data.
  • By using get accessor in the property implementation for accomplished read-only data.

Advantages

  • It is used for data hiding.
  • It is used for Re-usability.
  • flexibility increased by encapsulation.

Example


using System; 
public class MyCode {
      
    private String EmployeeName;
    private int EmployeeId;
    
    public String Name
    {
          
        get
        {
            return EmployeeName;    
        }
          
        set 
        {
            EmployeeName = value;
        }
          
    }
      
    public int Id
    {
          
        get 
        {
            return EmployeeId;    
        }
          
        set 
        {
            EmployeeId = value;
        }
          
    }
      
}
  
public class Program {
      
    static public void Main()
    {
        MyCode obj = new MyCode();
        obj.Name = "Roy";
        obj.Id = 1;
        Console.WriteLine("Name: " + obj.Name);
        Console.WriteLine("Id: " + obj.Id);
    }
}

OUTPUT

Name: Roy
Id: 1