Encapsulation

In object-oriented programming people often get confused with encapsulation and abstractions. Encapsulation in programming is the process of encapsulating data members and data methods into a single unit to hide it from another class.

Encapsulation is a strategy used as part of abstraction. It refers to the state of objects – objects encapsulate their state and hide it from the outside; outside users of the class interact with it through its methods but cannot access the classes state directly. So, the class abstracts away the implementation details related to its state.

It hides variables and method implementation in a class to prevent access from another class. Abstraction is used to hide irrelevant detail but at higher degrees (class, interface).

Abstraction and encapsulation are complementary concepts: abstraction focuses on the observable behavior of an object…encapsulation focuses on the implementation that gives rise to this behavior

Below image is best example to differentiate the encapsulation and abstraction. The surgeon and the lady visualized the animal differently. To design cat application we need to abstract our application’s as we can see on the on top-left rather than the top-right based on the feature required.

Encapsulation is the outline by the cat standing on the table. user should not care about the top-left or top-right based implementation, it expecting cat should see the cat as.

encapsulation vs abstraction

encapsulation vs abstraction c#, encapsulation in oop, encapsulation programming, encapsulation object oriented programming, encapsulation vs abstraction, encapsulation example
Image Credit – https://i.stack.imgur.com/iJhe5.png

For e.g. class, the class can encapsulate different variables, methods but act as in a single unit and access specifier decides which methods are accessible from another class.

Suppose we have StudentResult class which return student result in grade format. Below is the C# source code.

Example:

namespace EncapsulationDemo
{
    public class StudentResult
    {

        public Result GetResult(int studentId)
        {
            return new Result
            {
                AcademicGrade = GetAcademicScore(studentId),
                SportGrade = GetSportActivityScore(studentId),
                AttendanceGrade = GetAttendance(studentId),
                ExtracurricularActivityGrade = GetExtracurricularActivityScore(studentId)
            };
        }

        private Grade GetAcademicScore(int studentId)
        {
            //Goto database
            //Get the score from database
            //perform some logic and return the result
            return Grade.A;
        }

        private Grade GetAttendance(int studentId)
        {
            //Goto database
            //Get the score from database
            //perform some logic and return the result
            return Grade.A;
        }

        private Grade GetSportActivityScore(int studentId)
        {
            //Goto database
            //Get the score from database
            //perform some logic and return the result
            return Grade.A;
        }

        private Grade GetExtracurricularActivityScore(int studentId)
        {
            //Goto database
            //Get the score from database
            //perform some logic and return the result
            return Grade.A;
        }
    }
}

Grade enum

namespace EncapsulationDemo
{
    public enum Grade
    {
        A,
        B,
        C,
        D
    }
}

Result class

namespace EncapsulationDemo
{
    public class Result
    {
        public Grade AcademicGrade { get; set; }
        public Grade AttendanceGrade { get; set; }
        public Grade SportGrade { get; set; }
        public Grade ExtracurricularActivityGrade { get; set; }
    }
}

Main Class

namespace EncapsulationDemo
{
    class Program
    {
        static void Main()
        {
            StudentResult studentResult = new StudentResult();
            var result = studentResult.GetResult(1);
        }
    }
}

We can see in the above StudentResult class all methods are private except the GetResult method.

Which is hiding all the methods of student class, so the client class is not aware that to get the result or to calculate result what is StudentResult class is doing internally.

Also, if we create an instance of StudentResult class in another class we can not access the other methods because all those are private.

access specifier in oop, access specifier encapsulation, encapsulation in oop, encapsulation in programming, encapsulation in java, encapsulation example, ,encapsulation vs abstraction, encapsulation in oop, encapsulation meaning, encapsulation in c++

You can read more about access specifier/modifier from below.

Why we need Encapsulation in programming?

As we have seen encapsulation is used to hide class level objects which provides complete ownership in class to restrict the unwanted access of a class. The client would not be knowing what is going on under the hood. Since the implantation is hidden, we can make the change at any point. Which results in flexibility.

Also, sometimes we might need to change the variable access modifiers or needs only read-only properties, with encapsulation we easily maintain the program by changing in a particular class.
Encapsulation used to resolve the problem in the development/implementation

Helpful Resource


Conclusion

Encapsulation and Abstraction are very different but co-related concepts. encapsulation is the process of wrapping the information in such a way as to hide what should be hidden and make visible what is intended to be visible. Abstraction is a technique used to hide information while designing the complex system on a higher degree not limited to within a class.


Leave a Reply

Your email address will not be published. Required fields are marked *