我在学习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/