Question

Is there a way in Java to express that an attribute x of an object o can be accessed (I mean by dot notation o.x) only by o itself? To be clear: I'm talking about object-level access as in Smalltalk, not class-level access (thus private is not private enough)?

I'm sorry - I'm sure this has been asked many times before, but I seem to pick the wrong keywords when searching.

Was it helpful?

Solution

It is not possible in Java (nothing is more private than the fields marked as "private"), but if you think about it, it is also logical: you can modify private fields of other objects only in the common class source code, and if you control the class source code, you could do any bad or good things anyway.

BTW, you can access even private variables of other classes via reflection, if there is no security manager installed, or the policy of the security manager allows it, see this: Why is it allowed to access Java private fields via reflection?

OTHER TIPS

What you want to do is not possible. Every object has its own set of instance variables and can be accessed through that object only as long as they aren't static. So in short, if you want an attribute of Java object accessible by that object only, keep that object alive :).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top