scala - Scala其他实例的 protected 成员

标签 scala protected

我在学习Scala时遇到了困难。我有一个基本上等同于此的继承层次结构:

class A {
    protected def myMethod() = println("myMethod() from A")
}

class B extends A {
    def invokeMyMethod(a: A) = a.myMethod()
}

但是尝试编译此示例时,出现错误“test.scala:7:错误:无法在A中访问方法myMethod”。

来自Java,我的理解是 protected 成员应该可以在派生类的任何位置进行访问,而且我从没见过任何东西可以告诉我Scala中的 protected 成员受实例的限制。有人对此有解释吗?

最佳答案

引用Scala Language Specification:

A protected identifier x may be used as a member name in a selection r .x only if one of the following applies:

– The access is within the template defining the member, or, if a qualification C is given, inside the package C, or the class C, or its companion module, or

– r is one of the reserved words this and super, or

– r ’s type conforms to a type-instance of the class which contains the access.



这三个规则定义了何时确切允许一个实例访问另一个实例的 protected 成员。需要注意的一件事是,根据最后一条规则,当B扩展A时,A实例可以访问另一个B实例的 protected 成员……但是B实例不能访问另一个A的 protected 成员!换句话说:
class A {
    protected val aMember = "a"
    def accessBMember(b: B) = b.bMember // legal!
}

class B extends A {
    protected val bMember = "b"
    def accessAMember(a: A) = a.aMember // illegal!
}

关于scala - Scala其他实例的 protected 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4621853/

相关文章:

scala - 午餐时间 "Introduction to Scala"谈话的建议内容

c++ - 如何从派生类访问基类中的 protected 方法?

c++ - 当作为参数传递时,为什么不能在子类函数中访问 protected 父类(super class)成员?

scala - 访问基类的 protected 成员

java - 无法下载 scala-library-2.11

xml - Scala:合并 xml 数据树?

java - 在 Scala 中使用 Java 类时出现 "ambiguous reference to overloaded definition"

scala:如何在程序运行前知道程序有未处理的异常?

java - 不同包的子类继承?

java - 如何访问父类(super class)动态对象的 protected 成员变量