Is there a notion of object-private in any OOP language ?? I mean more restrictive than the classic private access ?
Private (or class-private) restricts the access to the class itself. Only methods that are part of the same class can access private members.
object-private : restricts the access to the object itself. Only methods objects that can access members and it will be impossible to write :
public class Person {
private String secret;
public String othersSecret;
public void snoop(Person p) {
othersSecret = p.secret; //will be prohibited by the compiler
}
EDIT :
If it exist can you give me some examples ... if not do you think it's interesting to have this kind of feature ?? and is it possible to simulate it in others OOP languages ??
EDIT 2 : Thanks you guys, all the answers were very instructive ...
Until now, the temporary conclusion :
The instance-private notion exists in 2 languages :
1 - Smalltalk after hours of googling :) I found the language behind this concept !!
The state an object holds is always private to that object. Other objects can query or change that state only by sending requests (messages) to the object to do so.
2 - Ruby thanks to Logan :
One person summed up the distinctions by saying that in C++, “private” means “private to this class”, while in Ruby it means “private to this instance”. What this means, in C++ from code in class A, you can access any private method for any other object of type A. In Ruby, you can not: you can only access private methods for your instance of object, and not for any other object instance (of class A).
In ruby, per-object private is the only private (you have to use protected
to get class private behavior).
E.g. foo.rb:
class A
private
def a=(x)
@a=x
end
public
def a
@a
end
def b(c)
c.a = 2
end
end
a1 = A.new
a2 = A.new
a1.b(a2)
Running it, we get
foo.rb:12:in `b': private method `a=' called for #<A:0xb7c9b6e0> (NoMethodError)
from foo.rb:18
Of course there are ways around this, but there almost always are.
I think the feature you want could be implemented by, figuratively, not allowing Persons to communicate directly. To achieve this with minimal effort you can introduce an interface, which would not provide access to things you want to make secret.
public interface IPerson
{
void communicateFormally();
}
public class Person : IPerson
{
private String secret;
public String othersSecret;
public void snoop(IPerson p) {
othersSecret = p.secret; //will be prohibited by the compiler
}
...
}
Now, this could be "hacked" by an ugly cast, but I think that's the problem of the one hacking.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With