What's the difference between abstraction and encapsulation?

前端 未结 24 1105
攒了一身酷
攒了一身酷 2020-12-22 17:16

In interviews I have been asked to explain the difference between abstraction and encapsulation. My answer has been along the lines of

  • Abstraction<

24条回答
  •  轮回少年
    2020-12-22 17:47

    Abstraction : Abstraction is process in which you collect or gather relevant data and remove non-relevant data. (And if you have achieved abstraction, then encapsulation also achieved.)

    Encapsulation: Encapsulation is a process in which you wrap of functions and members in a single unit. Means You are hiding the implementation detail. Means user can access by making object of class, he/she can't see detail.

    Example:

     public class Test
       {
        int t;
        string  s;
     public void show()
      {
       s = "Testing";
       Console.WriteLine(s);
       Console.WriteLine(See()); // No error
      }
    
     int See()
      {
       t = 10;
       return t;
      }
    
     public static void Main()
      {
      Test obj =  new Test();
      obj.Show(); // there is no error
      obj.See(); // Error:- Inaccessible due to its protection level
      }
     }
    

    In the above example, User can access only Show() method by using obj, that is Abstraction.

    And See() method is calling internally in Show() method that is encapsulation, because user doesn't know what things are going on in Show() method.

提交回复
热议问题