Scala学习第七天 Scala类的属性和对象私有字段实战详解

信息来源于 DT大数据梦工厂微信公众账号:DT_Spark
DT大数据梦工厂群号:302306504王家林老师微信号:wangjialinandroid
内容:
1、Scala类的使用实战
2、getter与setter实战
3、对象私有属性实战

一、Scala类的实战
1、var可改变值的,private级别,与java不同的是这个age必须赋值

//没有Public,默认是Public级别
class Person{
  private var age = 0  
  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)
  /*调用Student类自动生成的Student.setAge,在Scala ,是age_,来赋值*/
  student.age = 10  
   /*通过Student类自动生成的 Student.getAge,在Scala, 是age,来取值打印*/
  println(Student.age)  
}

二、getter与setter实战
val自动生成final和getter,也就是只读属性

class Student{
 private var privateAge = 0
 val name = "Scala"  
 def age = privateAge
}
object HelloOOP{
  def main(args:Array[String]:Unit = {
  val student = new Student
  //Student.name = 10 报错,只能读不能写
  println(Student.name)
}

三、对象私有属性实战
1、private[this]:类的方法只能访问自己对象的私有属性,不能访问其他对 象的属性,也就是当前对象私有
2、类的方法可以访问这个类的所有私有字段

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对象私有,不能被别的对象访问*/

Scala 深入浅出实战经典(1-64讲)完整视频、PPT、代码下载:

百度云盘:http://pan.baidu.com/s/1c0noOt6

腾讯微云:http://url.cn/TnGbdC

360云盘:http://yunpan.cn/cQ4c2UALDjSKy 访问密码 45e2
Scala视频及其更新和其他资料(Spark公开课、安卓基础、移动互联网)下载:
百度云盘:http://pan.baidu.com/share/home?uk=4013289088&view=share#category/type=0

你可能感兴趣的:(scala,类的属性,对象私有字段)