c#Interview

The Best Thing about Abstraction And Encapsulation

One of the most frequently asked questions in interviews is about abstraction and Encapsulation. You can answer that it helps in the data hiding process and shows only the relevant information. But try to tell in a real-time approach or with any code example. Most interviewers’ expectations will be an example approach to explain the abstraction or Encapsulation.

Let see a simple example.

 public class DataProvider
     {
         public void  ValidateStudentInfo()
         {
             //Student validation logic
         }
  
         public void AddStudent()
         {
             //Database logic to add student
         }
  
     }
  
     public class Program
     {
         static void Main(string[] args)
         {
             DataProvider dataProvider = new DataProvider();
             dataProvider.AddStudent();
         }
     } 

The Addstudent method is getting called to save the student information in the above code, but the ValidateStudentInfo process forgets to implement it. So there is a possibility to store the invalid information in the student database.

To overcome this situation, abstraction and Encapsulation will be helpful.

 //Abstraction
     public class DataProvider
     {
         //Encapsulation
         private void  ValidateStudentInfo()
         {
             //Student validation logic
         }
  
         public void AddStudent()
         {
             this.ValidateStudentInfo();
  
             //Database logic to add student
         }
     }
  
     public class Program
     {
         static void Main(string[] args)
         {
             DataProvider dataProvider = new DataProvider();
             dataProvider.AddStudent();
         }
     } 

The ValidateStudentInfo method access specifier is changed from a public to a private method and wrapped inside the AddStudent process in the above example. So, the ValidateStudentInfo logic part becomes Encapsulation, and the AddStudent method will take care of the validation.

It can be related to real-world examples asĀ  follows:

  • DataProvider Class is like a TV Remote (Abstraction).
  • ValidateStudentInfo private method is like a Remote Internal Parts (Encapsulation).
  • AddStudent public method is like a Remote Buttons (Showing only relevant information and no need to worry about internal mechanism).