One important feature is that encapsulation can hide some data members and function members. The The purpose of hiding is to protect object integrity so caller will not accidentally modify the object state and corrupt the object. It is not a mechanism to protect secret information. I highlight the word "accidentally". Hiding does not prevent you from access these hidden members intentionally. In java private members can be accessed or modified by reflection. They can be modified or replaced through instrument. This is how many mock frameworks works. This principle sounds good, but there are other better ways to do it.
Here are one piece of code I have in one of my project:
static Field field;
static {
try {
field = DynamicClassWriter.class.getDeclaredField("parentClass");
field.setAccessible(true);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
We could do this: prefix any object member we want to hide with "__". When developer saw "__" prefix, it is like a warning "use it as your own risk". IDE can treat any member with "__" prefix as it treats private member right now. Compiler can also give a warning if "__" members are accessed externally. At the same time, developer can access "__" member at his own risk. Isn't this a better approach?
If you are reading this post, add your comment. I'd like to know what you think on this topic.