大資料學習:抽象類

andy888168發表於2019-10-11

大資料學習:抽象類

5.3.1 抽象類的定義

定義一個抽象類:

如果某個類至少存在一個抽象方法或一個抽象欄位,則該類必須宣告為abstract。

abstract   class  Person{
// 沒有初始值,抽象欄位
var  name:String
// 沒有方法體,是抽象方法
def  id: Int

}

class  Employ extends  Person{
var  name:String= "Fred"
// 實現,不需要 overide 關鍵字
def  id = name. hashCode

}

5.3.2 抽象類的應用

定義帶有抽象型別成員的特質:

trait  Buffer {
   type  T
   val  element: T
}

定義一個抽象類,增加型別的上邊界

abstract   class  SeqBuffer extends  Buffer {
   type  U
   //
   type  T <: Seq[U]
   def  length = element. length
}

abstract   class  IntSeqBuffer extends  SeqBuffer {
   type  U = Int
}

abstract   class  IntSeqBuffer extends  SeqBuffer {
   type  U = Int
}

// 使用匿名類將 type T 設定為 List[Int]
def   newIntSeqBuf (elem1: Int, elem2: Int): IntSeqBuffer =
   new  IntSeqBuffer {
        type  T = List[U]
        val  element = List(elem1, elem2)
     }
val  buf = newIntSeqBuf ( 7 , 8 )
println ( "length = "  + buf. length )
println ( "content = "  + buf. element )

 


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69947096/viewspace-2659536/,如需轉載,請註明出處,否則將追究法律責任。

相關文章