您的位置:首页 > 其它

Scala访问修饰符

2015-12-18 20:11 429 查看
类或对象的成员可以使用访问修饰符
private
protected
public
,默认访问修饰符为
public


私有成员:

私有成员只能被包含该成员的类或对象内部方法或类访问。

class Outer {
class Inner {
private def f() { println("f") }
class InnerMost {
f() // OK
}
}
(new Inner).f() // Error: f is not accessible
}


保护成员:

受保护的成员是从该成员定义的类的子类才能访问。

package p {
class Super {
protected def f() { println("f") }
}
class Sub extends Super {
f()
}
class Other {
(new Super).f() // Error: f is not accessible
}
}


访问
f
在其他类中是不允许的,因为其他没有从超类继承。在Java中,是允许的,因为它们是在同一个包中。

公共成员:

未标示私有或受保护的每一个成员是公开的。不需要明确使用修饰符public。这样的成员可以从任何地方访问。

class Outer {
class Inner {
def f() { println("f") }
class InnerMost {
f() // OK
}
}
(new Inner).f() // OK because now f() is public
}


保护范围:

Scala中的访问修饰符可以增加使用修饰符。形式:
private[X]
protected[X]
的修饰符意味着访问私有或受保护“达到”
X
,其中
X
代表了一些封闭的包,类或单个对象。

package society {
package professional {
class Executive {
private[professional] var workDetails = null
private[society] var friends = null
private[this] var secrets = null

def help(another : Executive) {
println(another.workDetails)
println(another.secrets) //ERROR
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  scala