I instantiate two objects of one class, and one object accesses and changes private fields of the other object. I believe this violates the private access control. It breaks encapsulation in OOP. However, I find that both C++ and Java seem to allow this "violation". Please enlighten me why this "violation" is allowed!
Sample C++ code:
#include <iostream>
using namespace std;
class Person
{
private:
int age;
public:
void changeAge(Person & p, int k) // change peer object's private fields
{
p.age = k;
};
Person(int k)
{
age = k;
};
void showAge()
{
cout << this->age << endl;
};
};
int main()
{
Person a(10);
a.showAge();
Person b(11);
b.changeAge(a, 20); // I think the compiler SHOULD generate access violation error
a.showAge();
b.showAge();
return 0;
};
The output is:
10
20
11
You may write similar code for Java, and you'll have the same output.
I consulted http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html I understand private fields are visible at the class level. I believe that's probably the only viable reason for this "violation" to take place. (Please add more reasons if you can!)
However, I don't think it makes sense to allow this "violation", because it breaks encapsulation in OOP. The fact that we both are human beings does NOT imply that I can access and modify your private stuff. It's no longer your "private stuff" if I can.
Please enlighten me! Is the "violation" a bug of C++ & Java? If I'm wrong, please let me know!
It is definitely not a "bug" in either language. They are well established, and were designed to operate this way. Access controls operate at the class level, not the object level. So when Person
makes something private, that means that only code in the Person
class can manipulate it, but the object in question is irrelevant.
The point was to isolate knowledge of the internals of objects to particular pieces of code, not to ensure that one object couldn't manipulate another one.
Don't make the mistake of thinking that OOP is some well-established set of rules. Many different languages implement different ideas from OO, and there are differences among all of them. If a resource tells you definitively that OO "means" any specific thing, then they are misleading you. There's plenty that's open to interpretation by language designers and program authors.