实现多继承,注意观察父子类构造器的执行顺序
1.先父后子
2.有多个父类,按书写顺序从左向右执行
object Class013 {
trait A {
println("A")
}
trait BB {
println("BB")
}
trait B extends BB {
println("B")
}
trait CC {
println("CC")
}
trait C extends CC {
println("C")
}
class Class1 extends C with A with B {
println("Class1")
}
def main(args:Array[String]): Unit = {
new Class1()
}
}
object Class015 {
class Person {
val name: String = "xx" // 公开
protected val birthday: String = "2000-10-10" // 本类、子类可访问
private val password: String = "123456" // 本类、伴生对象可访问
private[this] val money: Int = 100 // 仅当前对象可访问
def t(): Unit = {
println(money) // 本对象内可访问private[this]
}
}
// Person的伴生对象(可访问private成员)
object Person {
def test(p: Person): Unit = {
println(p.password) // 伴生对象可访问private
// println(p.money) // 编译错误:private[this]无法在其他实例访问
}
}
// 2. 子类Son
class Son extends Person {
def showBirthday(): Unit = {
println(birthday) // 子类可访问protected
}
}
// 3. 程序入口object
object Main {
def main(args: Array[String]): Unit = {
val p1 = new Person()
println(p1.name) // 公开成员可访问
// println(p1.birthday) // 编译错误:protected无法在外部访问
val son = new Son()
son.showBirthday() // 子类访问protected
Person.test(p1) // 伴生对象访问private
}
}
}