scala-07Scala类的属性和对象私有字段实战详解
2015-08-13 19:23
453 查看
第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对象私有,不能被别的对象访问
}
一、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对象私有,不能被别的对象访问
}
相关文章推荐
- wcf系列学习5天速成——第三天 分布性事务的使用 有时间再验证下 不同库的操作
- 两个整数比较大小(指针函数的调用)
- 共享/出售即时通讯源代码,类似微信陌陌,全新定义基于Tiagse的社交聊天系统
- nginx + tomcat 页面无法展示
- UITextField 详解
- HDU5379.Mahjong tree
- Howie带你云上飘-新浪云
- scala-06Map、Tuple、Zip实战解析
- 一旦专利
- leetcode 133 —— Clone Graph
- scalability system design
- hdu5240
- Oracle中group by 的扩展函数rollup、cube、grouping sets
- oracle 10g的备份和还原
- 僵尸进程(zombie process)
- 使用Spring框架的步骤
- oracle 10g的备份和还原
- kphp开源框架学习篇之kphp框架整合smarty的全面讲解!
- [CQOI2012]组装 (非贪心,数学解法)
- iOS百度地图SDK基本配置和使用