Whenever I prepare for interview, I always think of this basic concept and always find it confusing. Well, may be because I always thought about both of the hiding implementations. Also, I was under impression that encapsulation complements abstraction. I always had a question, if both hides implementation and complements each other then why two different names or why Encapsulation Vs Abstraction.
In the section, given below, I am going to discuss both. As per my understanding, encapsulation refers to-
Encapsulation
In OOPS, an encapsulation allows us to wrap and control access of the logically grouped data. Yes, encapsulation means hiding the data. Lets see the class, given below. Its a simple class of Student, which encapsulates student properties and methods.
Code
- public class Student
- {
- public string FirstName {get; set;}
- public string LastName {get; set;}
- public DateTime DateOfBirth {get; set;}
- public bool Add(Student student)
- {
- ........Some Code
- }
- public List All()
- {
- ........Some Code
- }
- public bool Delete(Student student)
- {
- ........Some Code
- }
- }
Suppose, we want to implement one more class for teachers. I used to do is to copy student class and replace all Student with Teacher, because I always know the students and teachers both are human and have similar properties and methods.
Code
- public class Teacher
- {
- public string FirstName {get; set;}
- public string LastName {get; set;}
- public DateTime DateOfBirth {get; set;}
- public bool IsContract {get; set;}
- public bool Add(Teacher student)
- {
- ........Some Code
- }
- public List All()
- {
- ........Some Code
- }
- public bool Delete(Teacher student)
- {
- ........Some Code
- }
- }
Abstraction
We canr also say, why not creating an interface or an abstract class and implement it to the class, whenever we want similar implementation. Yes, we can absolutely do that and it is the preferred way of doing it. What does Abstraction mean? Does it mean Abstraction complements Encapsulation? Not really. Here, we are only generalizing the behavior of similar objects. Also, abstraction always comes first, which means you draft your Application design on paper or UML diagram. Figure out similar objects and implement abstract classes or interfaces. In abstraction, we are not basically hiding the data but here, the goal is to overview behavior of the objects.
Code
- interface IMember
- {
- bool Add(Member member);
- bool Delete(Member member);
- List Members();
- }
-
- public class Student: IMember
- {
-
- }
- public class Teacher: IMember
- {
-
- }
Conclusion: Encapsulation always means the data is hiding and controlling access, while abstraction means generalizing the objects. Hope, I explained it well. Please do not hesitate to leave the comments/corrections.
Enjoy!!!