第11章 泛型
package chapter11
object Test01_Generics {
def main(args: Array[String]): Unit = {
// 1. 协变和逆变
val child: Parent = new Child
//class MyCollection[+E] {}
// val childList:MyCollection[Parent] = new MyCollection[Child]
//class MyCollection[-E] {}
val childList: MyCollection[SubChild] = new MyCollection[Child]
// 2. 泛型上下限
def test[A<:Child](a:A):Unit={
println(a.getClass)
println(a.getClass.getName)
}
//test[Parent](new Child) // error,函数定义了泛型上限
test[Child](new Child)
test[Child](new SubChild)
test[SubChild](new SubChild)
//test[SubChild](new Child) // error 不能将父类的引用赋值给子类
}
}
// 定义继承关系
class Parent {}
class Child extends Parent {}
class SubChild extends Child {}
// 定义带泛型的类型集合
class MyCollection[-E] {}