第7讲:Scala类的属性和对象私有字段实战详解
一、Scala类
//没有Public,默认是Public级别
Class Person{
Private var age = 0 //var可改变值的,private级别,与java不同的是这个age必须赋值
Def increment(){age += 1}
Def current = age
}
Class Student{
Var age= 0
//声明一属性,默认private,与java不同,默认生成age的getter,setter,在scala对应为age的age,age_
}
Object HelloOOP{
Def main(args:Array[String]:Unit = {
Val person = new Person()
Person.increment()
Println(person.current)
}
二、getter与setter实战
Val student = new Student
Student.age = 10
//调用Student类自动生成的Student.setAge,在Scala,是age_ ,来赋值
Println(Student.age)
//通过Student类自动生成的Student.getAge,在Scala,是age,来取值打印
Class Student{
private var privateAge = 0
val name = "Scala" //自动生成final和getter,也就是只读属性
def age = privateAge
//限定一个成员只能归当前对象所有,为不能归当前对象的类的方法去使用
}
Object HelloOOP{
Def main(args:Array[String]:Unit = {
Val student = new Student
//Student.name = 10 报错,只能读不能写
Println(Student.name)
}
三、对象私有属性实战
Class Student{
private[this] var privateAge = 0
//类的方法只能访问自己对象的私有属性,不能访问其他对象的属性,也就是当前对象私有
val name = "Scala" //自动生成final和getter,也就是只读属性
def age = privateAge
//方法可以访问这个类的所有私有字段
def isYonger(other : Student) = privateAge < other.privateAge
//若privateAge设为对象私有,则报错,因为other是Student派生的对象,那么other中也有这个字段,属于other对象私有,不能被别的对象访问
}