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 } } } }
相关文章推荐
- Windows下Scala环境搭建
- Windows7下安装Scala 2.9.2教程
- Scala代码实现列出Hadoop 文件夹下面的所有文件
- ClassNotFoundException:scala.PreDef$
- XML 文件解析--含Unicode字符的XML文件
- 分分钟掌握快速排序(Java / Scala 实现)
- Scala极速入门
- Spark初探
- Scala实现REST操作
- Scala method call syntax
- 关于Scala多重继承的菱形问题
- Scala 高阶函数(high-order function)剖析
- Scala Monad Design Pattern
- Spray.io搭建Rest服务
- Spray.io搭建Rest — 支持Twirl模板并部署
- 搭建hadoop/spark集群环境
- Akka (actors) remote example
- scala工具库
- scala-协变、逆变、上界、下界
- scala-常用函数介绍