定义一个抽象类:
如果某个类至少存在一个抽象方法或一个抽象字段,则该类必须声明为abstract。
abstract
class
Person{
//
没有初始值,抽象字段
var
name:String
//
没有方法体,是抽象方法
def
id: Int
}
class
Employ
extends
Person{
var
name:String=
"Fred"
//
实现,不需要
overide
关键字
def
id = name.
hashCode
}
定义带有抽象类型成员的特质:
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博客 ” ,链接:https://blog.itpub.net/69947096/viewspace-2659536/ ,如需转载,请注明出处,否则将追究法律责任。