Monday, February 1, 2010

Explain the use of encapsulation.

Encapsulation hides the internal state and behavior of an object. Encapsulation if used with access modifiers such as private, public, protected. It provides a way to protect data.

public class MyClass
{
       private string name;
       public string Name
       {
            get
            {
                 return name;
            }
            set
            {
                   name = value;
            }
      }
}
public class main
{
        public static int Main(string[] args)
        {
               MyClass myclass = new MyClass();
               myclass.name = "Communication";
               Console.WriteLine("The name is :{0}", myclass.Name);
               return 0;
       }
}

See use of encapsulation through properties for accessing and setting the values.

0 Comments: