Difference between Encapsulation and Abstraction

后端 未结 15 1167
萌比男神i
萌比男神i 2020-12-07 07:21

I had an interview today. I had a question from OOP, about the difference between Encapsulation & Abstraction?

15条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 08:03

    Encapsulation: Wrapping code and data together into a single unit. Class is an example of encapsulation, because it wraps the method and property.

    Abstraction: Hiding internal details and showing functionality only. Abstraction focus on what the object does instead of how it does. It provides generalized view of classes.

    int number = 5;
    string aStringNumber = number.ToString(); 
    

    Here, ToString() is abstraction. And how this mechanism number variable converted to string and initialize into aStringNumber is encapsulation.

    Let us take a real world example of calculator. Encapsulation is the internal circuits, battery, etc., that combine to make it a calculator. Abstraction is the different buttons like on-off, clear and other buttons provided to operate it.

提交回复
热议问题