Search code examples
oopencapsulation

Why to use "protected" in OOP?


i have a question that is haunting me for a long time. As you know there are some kind of encapsulation methods like protected, private or public. But the question is that why do we use protected or what or who do we protect these classes from? Basically why do they need to be protected? I learned that we use private when we dont want to access that object from other classes but what is the harm of that? What will happen if other classes access that object?

Please enlighten me

I really have no idea


Solution

  • Think of it as Levels of access.

    As you pointed out Private is used to protect the object from external access. You must also be knowing about the Public keyword which essentially allows access to all the members to external classes without any restriction.

    But here's the issue Private is way too much restrictive and Public is way too open in a way they allow access.

    That would be nice if we have a Keyword that is somewhere in the middle right? this is where Protected comes into the picture.

    Protected members can only be accessed by the class itself or the derived classes.

    Coming to your last question: What is the harm in accessing those objects?

    The main reason, as a class, you are not supposed to know what the other class does. primarily due to security and design issues. Simple example let's suppose you have an SDK of any bank which your application uses. and now imagine you are able to alter its private members suppose recipient, amount, account no. imagine how damaging it is. Thus the restricted access.

    Hope this helps and gives clarity with real-life example.