c++中:
public:
外部使用时(实体对象)可见、子类及本类内部/ 成员函数、友元函数可见
protected:
子类及本类内部/ 成员函数、友元函数可见
private:本类内部/ 成员函数、友元函数可见 (默认private)
scala中class的字段默认是public:
class Person{
var age = 0
def increment = {age += 1}
def current = age
}
object test {
def main(args: Array[String]) {
val person = new Person
person.increment
println(person.current)
println(person.age)
}
}
如果字段被声明成private的,类外部的对象不能通过.字段名访问,但在类内部的成员函数可以访问其他对象的该字段,即字段是被类私有的
class Person{
private var age = 0
def increment = {age += 1}
def current = age
def isYounger(other:Person) = age<other.age
}
object test {
def main(args: Array[String]) {
val person = new Person
person.increment
println(person.current)
person.age
}
}
而字段如果被声明成private[this]的,字段是被对象私有的,成员函数不能访问其他对象的该字段
class Person{
private[this] var age = 0
def increment = {age += 1}
def current = age
def isYounger(other:Person) = age<other.age
}