Access modifiers are solely a compile time mechanism in C++. In Java however, they are enforced at runtime too, because Java also has a runtime typesystem, and it can dynamically (at runtime) create classes. So it needs to enforce access at runtime too for types it doesn't know about at compile time.
Why use access modifiers?
The sole purpose of access modifiers is to enforce design.
Say you have a class A
that you implemented
class A
{
public:
void DoSomething()
{
// use private member mPrivMember to do something
}
private:
int mPrivMember;
}
And some code using class A
:
A a_obj;
The above code can call a_obj.DoSomething()
, however they don't have direct access to mPrivMember, so a.mPrivMember
written outside class A
will not compile.
Now, why would you want some members accessible to outside code and some not?
Well, here is why: at the moment, the method DoSomething()
uses mPrivMember
to actually do stuff. But after some time, you might decide you want to refactor the code in DoSomething, to improve it. You found a different way to do something that doesn't involve using mPrivMember
anymore. So you delete mPrivMember
and reimplement DoSomething
some other way.
Now, if there was code outside your class using mPrivMember
, that code wouldn't compile anymore because you have deleted mPrivMember
when reimplementing DoSomething
. To prevent existance of such code, you restrict access to mPrivMember
. The mechanism to do that is through access qualifiers such as private
and protected
.
This allows you to refactor code in the future without worrying that other code might use internal members.
Recap
public
private
and protected
are compile time mechanisms in C++. They do not exist in the generated binary form of your program, and thusly such protections are not enforced. Anything is accessible from anywhere.
In Java however, classes can be created at runtime if I'm not mistaken. Which is the reason why it also has to check for access at runtime too so it can enforce them, thus Private
Public
and Protected
do exist in a Java binary.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…