language-agnostic - 是否存在具有基于对象访问级别的语言?

标签 language-agnostic access-levels

关于 Java、C#、C++ 和 PHP 中访问级别的一个常见误解是它适用于对象而不是类。也就是说,(比如说)X 类的一个对象不能看到另一个 X 的私有(private)成员。事实上,当然,访问级别是基于类的,一个 X 对象可以毫不费力地引用另一个对象的私有(private)成员。

是否存在具有基于对象访问级别的语言?它们是替代或补充基于类的访问吗?这个特性对程序设计有什么影响?

最佳答案

Ruby 具有基于对象的访问级别。这是来自 Programming Ruby 的引用:

The difference between "protected" and "private" is fairly subtle, and is different in Ruby than in most common OO languages. If a method is protected, it may be called by any instance of the defining class or its subclasses. If a method is private, it may be called only within the context of the calling object---it is never possible to access another object's private methods directly, even if the object is of the same class as the caller.



来源:http://whytheluckystiff.net/ruby/pickaxe/html/tut_classes.html#S4

Java 和 Ruby 之间的示例差异

java
public class Main {
    public static void main(String[] args) {
        Main.A a1 = new A();
        Main.A a2 = new A();

        System.out.println(a1.foo(a2));
    }

    static class A
    {
        public String foo(A other_a)
        {
            return other_a.bar();
        }

        private String bar()
        {
            return "bar is private";
        }
    }
}

// Outputs
// "bar is private"

ruby
class A
  def foo other_a
    other_a.bar
  end

  private
  def bar
    "bar is private"
  end
end

a1 = A.new
a2 = A.new

puts a1.foo(a2)

# outputs something like
# in `foo': private method `bar' called for #<A:0x2ce9f44> (NoMethodError)

关于language-agnostic - 是否存在具有基于对象访问级别的语言?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1233375/

相关文章:

language-agnostic - 有没有没有控制结构或操作符的编程语言?

java - 我应该为每个公共(public)方法编写单元测试吗?

ruby-on-rails - Rails authlogic : How to make Levels?

c# - protected 和内部,不 protected 或内部

php - 访问级别和身份验证 (PHP/MYSQL)

algorithm - 研究时间序列的波动

unit-testing - 测试使用继承的类是否有任何最佳实践?

language-agnostic - 确定图中给定路径列表的边权重

java - 访问同一父字段中的 protected 字段?

ios - 由于 'internal' 保护级别 swift 4,扩展初始化程序无法访问