多继承

40 阅读1分钟

特质:trait

实现多继承,注意观察父子类的构造器的执行顺序

  1. 先父后子。
  2. 有多个父类,按书写顺序从左向右执行!
object Class23 {

  trait A {
    println("A")
  }

  trait B {
    println("B")
  }

  class class1 extends A with B {
    println("class1")
  }

  def main(args: Array[String]): Unit = {
    new class1()
  }
}
object Class23 {

  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()
  }
}
package level02

import java.io.FileWriter


object Class24 {
  // 在文件中写入日志
  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 {
    println(1)
    val filename = "11-28.log"
  }

  def main(args: Array[String]): Unit = {
    val filelogger = new MyFileLogger()
    filelogger.writeLog("今天上上scala课程")
  }
}

访问权限控制。

  1. 公开的。不写修饰符
  2. protected:保护的
    在类的外部不能访问;
    在子类中访问。
  3. private:私有的
    在类的外部不能访问;
    在子类中不能访问在伴生对象中可以访问!
  4. private [this]
    只能被当前对象使用
    在类的内部使用
object Person {
  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在类的外部无法访问
  // new Son().p1.birthday)
  new Son()
  // 3. 在伴生对象中访问 类的私有成员
  Person.test(p1)
}