Are there any programming languages providing object-level access control/protect?
public class ProtectedClass {
private String name;
public static void changeName(ProtectedClass pc, String newName) {
pc.name = newName;
}
public ProtectedClass(String s) { name = s; }
public String开发者_开发问答 toString() { return name; }
public static void main(String[] args) {
ProtectedClass
pc1 = new ProtectedClass("object1"),
pc2 = new ProtectedClass("object2");
pc2.changeName(pc1, "new string"); // expect ERROR/EXCEPTION
System.out.println(pc1);
}
} ///:~
Considering above Java source code,it could easily concluded that the Java programming language could only provide class-level access control/protect.Are there any programming languages providing object-level access control/protect?
thanks.
P.S:This problem is derived from this question Java: Why could base class method call a non-exist method?I want to give my appreciation to TofuBeer.
Scala has an object-private scope:
class A(){
private[this] val id = 1
def x(other : A) = other.id == id
}
<console>:6: error: value id is not a member of A
def x(other : A) = other.id == id
It compiles if you change the visibility to private:
class A(){
private val id = 1
def x(other : A) = other.id == id
}
精彩评论