依旧继承
注意父子继承顺序
trait A {
println("A")
}
trait B {
println("B")
}
class Class1 extends A with B{
println("Class1")
}
def main(args: Array[String]): Unit = {
new Class1()
}
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 B with A{
println("Class1")
}
运行结果为
CC C BB B A Class1
结果是先执行父类 cc 再执行子类c
加了lazy才能输出程序内容
trait FileLogger {
val fileName:String
lazy val fileWriter = new FileWriter(fileName,true)
def writeLog(msg:String):Unit = {
fileWriter.write(msg)
fileWriter.close()
}
}
class MyFileLogger extends FileLogger{
val fileName = "11-26.log"
}
def main(args: Array[String]): Unit = {
val fileLogger = new MyFileLogger()
fileLogger.writeLog("今天上午上scala课程")
}
权限访问控制,里面有再半生对象中的可访问与不可访问的解析
object class4 {
def test(p:Person): Unit = {
// private 在伴生对象中可以访问!
println(p.password)
// private[this] 在伴生对象中不能访问的
// println(p.money)
}
}
class Person(){
var name:String = "xx"; // 公开的
protected var birthday:String = "2000-10-10"
private var password:String="123456"
private[this] var money:Int=100
def t():Unit = {
println(money)
}
}
class Son extends Person(){
// 2. protected在子类中可访问
println(birthday)
// 3. private在子类中不能访问的
// println(password)
}
def main(args: Array[String]): Unit = {
val p1 = new Person()
println(p1.name)
// 2. protected在类的外部无法访问
// println(p1.birthday)
new Son()
// 3. 在伴生对象中访问 类的私有成员
Person.test(p1)
}
```
```