scala 抽象类与特质

抽象类

object s22_abstractClass {
  def main(args: Array[String]): Unit = {
    var man = new Men
    println(man.getId())
    println(man.gender, man.name)
  }

}

abstract class Person1 {
  // 抽象类不能被实例化
  // 抽象类可以有抽象字段,没有初始值
  // 可以有正常字段和正常方法
  var name = "zhangsan"
  var gender: String
  var age: Int

  // 抽象方法没有方法体
  def getId: Int
}

class Men extends Person1 {
  // 需要实现抽象字段和抽象方法
  var gender = "male"
  var age = 24

  override def getId() = {
    name.hashCode
  }
}

输出

-1432604556
(male,zhangsan) 

特质

// 定义一个带抽象方法的特质

trait Iterator[A] {
  // 泛型
  def hasNext: Boolean

  def next(): A
}

// 定义一个带实现的特质
trait Consolelogger {
  def log(mes: String): Unit = {
    println(mes)
  }

  def log1(mes: String, n: Int): Unit
}

//定义一个类实现特质, 第一个用extends,后面用with
class IntIterator(to: Int) extends Iterator[Int] with Consolelogger {
  var curr = 0

  override def hasNext: Boolean = curr < to

  override def next(): Int = {
    if (hasNext) {
      log("hasNext")
      val t = curr
      curr += 1
      t
    } else -1
  }

  override def log1(mes: String, n: Int): Unit = {
    // 传入参数需要保持一致
    for (x <- 1 to n) {
      println(mes)
    }

  }
}

object s23_trait {
  def main(args: Array[String]): Unit = {
    val ite = new IntIterator(10)
    while (ite.hasNext) {
      println(ite.next())
    }
  }

}

 

trait Logger24 {
  def log(mes: String)

  def warning(mes: String): Unit = {
    log("WARNING: " + mes)
  }

  def info(mes: String): Unit = {
    log("INFO: " + mes)
  }
}

trait ConLogger extends Logger24 {
  override def log(mes: String): Unit = println(mes)
}

trait TimeStamplogger extends ConLogger {
  override def log(mes: String): Unit = super.log(s"${java.time.Instant.now()}$mes")
}

trait ShortenLengthLogger extends ConLogger {
  val maxLength = 30

  override def log(mes: String): Unit = super.log(
    if (mes.length <= maxLength) mes
    else {
      s"${mes.substring(0, maxLength - 3)}..."
    }
  )
}


class Account {
  protected var banlance: Double = 100.0
}

class SavingAccount extends Account with ConLogger {
  def withdraw(amount: Double): Unit = {
    if (amount > banlance) warning("Insufficient Banlance")
    else {
      banlance -= amount
      info(s"You have withdraw ${amount}")
    }

  }
}

// 特质可以给类提供可以堆叠的改变
object s24_trait {
  def main(args: Array[String]): Unit = {
    val ac1 = new SavingAccount with ConLogger with TimeStamplogger with ShortenLengthLogger
    val ac2 = new SavingAccount with ConLogger with ShortenLengthLogger with TimeStamplogger
    // 混入顺序不同对结果的影响
    ac1.withdraw(20)
    ac2.withdraw(20)
  }
}

 

 

 

你可能感兴趣的:(java,Scala)