What is the significance of encapsulation and java information hiding?

393    Asked by JamesLeeming in Java , Asked on Oct 6, 2022

Member variables of a class are typically hidden from the outside world (i.e., the other classes), with private access control modifiers. Access to the member variables are provided via public assessor methods. This follows the principle of information hiding. That is, objects communicate with each other using well-defined interfaces (public methods). Objects are not allowed to know the implementation details of others. The implementation details are hidden or encapsulated within the class. Information hiding facilitates reuse of the class.

I have a question why setting member variables as private and accessing these variables via a public method is more secure than direct access to member variables with a public modifier. These 2 ways achieve the same result, meaning it both changes the values of member variables. Can anybody explain to me more clearly?

Answered by James SCOTT

Because java information hiding is not a security measure. It's a human-oriented measure for improving understanding.

The point of making a field private is not to prevent it from being changed. If an attacker wants to change values, well, if they have access to your program's process, they can change the values easily, no matter how the source code defines those values. It's all just bits in memory or in a cache somewhere anyway.

Then what is the point? Information hiding makes it easier to reason about your program when someone else (or you, two months down) has to understand it or change it. By not exposing the exact fields that a class is composed of, it becomes easier to understand what purpose it serves, whether to use it or not, which methods to call etc. What would you rather do - call a method hitBrakes() or write flags.frictionCoefficient &= 0x487FD3?

But that's a large difference. Is a small difference such as the one between car.setPrice(12345) and car.price = 12345 really worthwhile? Oh yes, it is. By programming an accessor rather than exposing a public field, you have given yourself the option of changing the implementation of that assessor someday. Maybe it becomes necessary to include validating logic into that accessor, or even to make it inoperable and just retained for backward compatibility. With a public field, you can do none of those things without breaking client code.

And this is why information hiding is good - not because someone else must not see it, but because you don't want to see it. Information that isn't public cannot become a constraint on future development.

Your Answer


Parent Categories