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

时间:2009-12-23 10:07:11

标签: 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);
    }
} ///:~

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

感谢。

P.S:这个问题源于这个问题Java: Why could base class method call a non-exist method?我想对TofuBeer表示感谢。

1 个答案:

答案 0 :(得分:5)

Scala 有一个 object-private 范围:

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

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

class A(){
    private val id = 1
    def x(other : A) = other.id == id
}