好程序员大数据学习路线分享Scala系列之抽象类

87 阅读1分钟

好程序员大数据学习路线继续为大家分享分享Scala系列之抽象类

1抽象类的定义

定义一个抽象类:

如果某个类至少存在一个抽象方法或一个抽象字段,则该类必须声明为abstract。

abstract class Person{

//没有初始值,抽象字段

var name:String
//没有方法体,是抽象方法

def id: Int

}

class Employ extends Person{
var name:String="Fred"
//实现,不需要overide关键字

def id = name.hashCode

}

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)