Scala--繼承


一、擴展類

  class Persion{
    def display(){
      println("Hello")
    }
    final def display1(){   //聲明為final, 不能被重寫 override
      println("Hello1")
    }
  }

  class Employee extends Persion{ //extends 擴展,繼承Persion
    override def display() {   //override重寫 display方法
      println("H")
    }
  }

  val p = new Employee
  p.display()
  p.display1()

 

二、重寫方法

  class Persion{
    private var str = ""
    def display(){
      println("Hello")
    }
    final def display1(){   //聲明為final, 不能被重寫 override
      println("Hello1")
    }
    def info_= (newStr:String){  //info setter方法
      str = newStr
    }
    def info = str     //info getter方法
  }

  class Employee extends Persion{ //extends 擴展,繼承Persion
    override def display() {   //override重寫 display方法
      println(super.info +" H")
    }
  }

  val p = new Employee
  p.info="hello"
  p.display()
  p.display1()

調用超類的方法使用: super

 

三、類型檢查和轉換

  class Persion{
  }

  val p = new Persion
  if(p.isInstanceOf[Persion]){  //類型檢查
    println("p is instance of Persion")
  }
  else{
    println("p is not instance of Persion")
  }

  if(p.getClass == classOf[Persion]){ //p是 Persion對象,並不是Persion的子類,這樣檢查
    println("Yes")
  }

 

p is instance of Persion
Yes

 

四、受保護字段和方法

protected 可以被子類訪問

 

五、超類的構造

傳遞到超類的構造函數

  class Employee(name: String, age: Int, val salary: Double) extends
   Persion(name, age)

Scala類可以擴展java類

  class Square(x:Int , y: Int, width: Int) extends
  java.awt.Rectangle(x, y, width, width)

 

六、重寫字段

  class Persion(val name: String){
    override def toString = getClass.getName()+ "[name="+name+"]"
  }


  class SecretAgent (codename: String) extends Persion(codename){
    override val name = "secret"   //重寫 name
    override val toString ="secret" //重寫 toString
  }

  val p = new SecretAgent("hello")
  println(p.name)
  println(p.toString)

 

常用做法:用val重寫抽象的def

  abstract class Persion{
    def id :Int = 10
  }

  class Student(override val id:Int) extends Persion{
  }

  val p = new Student(4)
  println(p.id)

 

七、匿名字段

  class Persion(val name:String){
  }

  val alien = new Persion("Fred"){  //匿名子類   類型為 Persion{def greeting: String}
    def greeting = "Hi everybody"
  }

  def meet(p:Persion{def greeting: String}){
    println(p.name + " says:" + p.greeting)
  }

  meet(alien)

結果:

Fred says:Hi everybody

 

八、抽象類

  abstract class Persion(val name:String){ //抽象類
    def id:Int   //方法不用定義為抽象
  }

  class Student(name:String) extends Persion(name){ //繼承抽象類
    def id = name.hashCode  //實現抽象類中的方法, 不需要override關鍵字
  }
  
  val s = new Student("Jim")
  println(s.id)

 

九、抽象字段

  abstract class Persion{
    val id :Int
    var name : String
  }

  class Student(val id :Int) extends Persion{
    var name =""
  }

  val fred = new Persion{
    val id = 12
    var name = "Fred"
  }

  println(fred.id)
  println(fred.name)

結果:

12
Fred

 

十、構造順序和提前定義

  class Creature {
    val range: Int = 10
    val env: Array[Int] = new Array[Int](range)
  }

  class Ant extends Creature{
    override val range: Int = 2
  }

  val c = new Ant
  println(c.range)              //結果為2
  println(c.env.length)      //結果為0

  class Creature {
    lazy val range: Int = 10    //使用lazy
    val env: Array[Int] = new Array[Int](range)
  }

  class Ant extends Creature{
    override lazy val range: Int = 2  //使用lazy
  }

  val c = new Ant
  println(c.range)            
  println(c.env.length)        //返回結果為2

  class Creature {
      val range: Int = 10
      val env: Array[Int] = new Array[Int](range)
    }

    class Ant extends {            //使用提前定義  with Creature
      override val range: Int = 2
    }with Creature

    val c = new Ant
    println(c.range)
    println(c.env.length)      //結果返回2

 

十一、Scala繼承層次

Any 類繼承層次根節點

Nothing 類型沒有實例

Null 類型的唯一實例是null值

Nil 空列表, 空列表的類型是List[Nothing]

Unit 類型void

 

十二、對象相等性

  class Item(val desc: String, val value: Double){

    final override def equals(other: Any) ={   //參數使用 Any類型 ,重寫AnyRef equals方法
      val that = other.asInstanceOf[Item]
      if(that == null) false
      else desc == that.desc &&  value ==that.value  //判斷是否相等
    }

    final override def hashCode = 13 * desc.hashCode + 17 * value.hashCode //重寫 hashCode方法

  }

  val a = new Item("Apple", 14)

  val b = new Item("Apple", 23)

  if(a == b)
    println("Equal")

 

練習:

1.2.

object Chapter8 extends App{
  
  class BankAccount(initialBalance:Double){
    private var balance = initialBalance
    def deposit(amount:Double) = {balance += amount; balance}
    def withdraw(amount:Double) = {balance -= amount; balance}
    override def toString=s"money=$balance"
  }

  class CheckingAccount(initialBalance:Double) extends BankAccount(initialBalance:Double){
    val fee: Double = 1
    var count:Int = 3
    override def deposit(amount:Double) = {val new_amount=if(count>0) {count-=1;amount-fee} else amount;super.deposit(new_amount)} //存錢,扣除手續費,少存
    override def withdraw(amount:Double) = {val new_amount=if(count>0) {count-=1;amount+fee} else amount;super.withdraw(new_amount)}//取錢,扣除手續費,多扣
    def earnMonthlyInterest(c:Int = 3) {count = c}
  }

  val ba = new CheckingAccount(100)
  ba.deposit(100)
  println(ba)
  
}

4.

object Chapter8 extends App{
  abstract class Item {
    def name:String
    def price:Float
    def description:String
  }

  class SimpleItem (n: String, p: Float) extends Item{
    val name:String = n
    val price = p
    val description = s"$n is $p yuan"
  }

  class Bundle{
    import scala.collection.mutable.ArrayBuffer
    var items = new ArrayBuffer[Item]()

    def price = {
      var sum: Float = 0
      for(i<- items) {
        sum+=i.price
      }
      sum
    }
    def addItem(item:Item){items+=item}
    def description:String={s"price is $price yuan"}
  }
  
  val i1 = new SimpleItem("i1",100)
  val i2 = new SimpleItem("i2",201)

  val b = new Bundle()
  b.addItem(i1)
  b.addItem(i2)
  println(b.price)
}

5.

object Chapter8 extends App{

  class Point(x:Double, y:Double){
  }
  class LabelPoint(label:String, x:Double, y:Double)extends Point(x,y){
  }
  val lp = new LabelPoint("label", 100.21, 200.31)
}

6.

 

 

 

 

參考《快學Scala》


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM