是否有任何编程语言提供对象级访问控制/保护?

Jic*_*hao 1 programming-languages

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);
    }
} ///:~
Run Code Online (Sandbox Code Playgroud)

考虑到上面的Java源代码,可以很容易地得出结论,Java编程语言只能提供类级访问控制/保护.是否有任何编程语言提供对象级访问控制/保护?

谢谢.

PS:这个问题源自这个问题Java:为什么基类方法可以调用不存在的方法?我想对TofuBeer表示感谢.

Tho*_*ung 5

Scala有一个对象私有范围:

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
Run Code Online (Sandbox Code Playgroud)

如果您将可见性更改为私有,则编译它:

class A(){
    private val id = 1
    def x(other : A) = other.id == id
}
Run Code Online (Sandbox Code Playgroud)