加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – object-private Vs class-private

发布时间:2020-12-17 02:50:35 所属栏目:百科 来源:网络整理
导读:在任何OOP语言中是否存在对象私有的概念?我的意思是比经典的私人访问更具限制性? 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:限
在任何OOP语言中是否存在对象私有的概念?我的意思是比经典的私人访问更具限制性?

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:限制对象本身的访问.只有可以访问成员的方法对象才能编写:

public class Person {

private String secret;
public String othersSecret;

public void snoop(Person p) {
    othersSecret = p.secret; //will be prohibited by the compiler
}

编辑:

如果它存在,你可以给我一些例子……如果不是,你认为有这样的功能有趣吗?是否有可能在其他OOP语言中模拟它?

编辑2:
谢谢你们,所有答案都很有启发性……

到目前为止,临时结论:

instance-private概念以2种语言存在:

1 – 使用谷歌搜索后的Smalltalk :)我找到了这个概念背后的语言!

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感谢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).

解决方法

在ruby中,per-object private是唯一的私有(你必须使用protected来获取类私有行为).

例如. 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)

运行它,我们得到

foo.rb:12:in `b': private method `a=' called for #<A:0xb7c9b6e0> (NoMethodError)
    from foo.rb:18

当然有办法解决这个问题,但几乎总会如此.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读