润饰掌握符
package base
object obj {
def main(args: Array[String]): Unit = {
// 调用无参结构办法
val ps = new Person()
println(ps.name)
val person = new Person("小明")
person.name = "小张"
println(person.name)
// 自定义private 字段set办法应用
person.myAge = 1
println(person.myAge)
person.otherPerson(new Person("小李"))
}
}
class Person {
// 默许是public 会主动生成get和set办法
var name: String = _
// 不会主动生成get和set办法
val info1: String = "info1"
protected var info3: String = _
protected[this] var info4: String = _
// 在 base 包及包下面应用
protected[base] var info5: String = _
// 私有字段
private var age: Int = _
// age 的get办法,不能和字段名字雷同
def myAge: Int = age
// age 的set办法,不能和字段名字雷同,注意格局
def myAge_=(newAge: Int) {
age = newAge
}
private[this] val info2: String = "info2"
// private[this] 和 private的区分
def otherPerson(other: Person): Unit = {
println(this.age == other.age)
// 报错! 不能拜访仅在实例内部应用的字段
// println(this.info2.equals(other.info2))
}
// 生成有参结构办法
def this(name: String) {
// 调用无参结构办法
this()
// 初始化变量
this.name = name
}
}package base
object obj {
def main(args: