路径依赖路径1帖子中得出了结论:路径依赖的是路径的名称,与路径所引用的实例无关即类型无关
如果一个类中有抽象成员且有抽象类型,路径依赖的时候会是什么情况呢?
class Food
abstract class Animal{
type SuitableFood <: Food //抽象类型字段,且用限定符<:表示了是Food类型的子类
def eat(food:SuitableFood)
}
class Grass extends Food
class Cow extends Animal {
type SuitableFood = Grass
override def eat(food:Grass): Unit ={
println("eat " + food.toString)
}
}
class Fish extends Food
object PathDependTest {
def main(args: Array[String]): Unit = {
val animal:Animal = new Cow
val fish = new Fish
// animal.eat() //当输入到此时,IDEA提示 Animal.this.SuitableFood
// animal.eat(fish) //提示类型错误:需要animal.SuitableFood,但实际是Fish
// 这个错误提示的是:需要对象引用(animal)加上对象的类型字段(SuitableFood)
val grass = new Grass
// animal.eat(grass) //还是提示错误:需要animal.SuitableFood,但实际是Grass
val g = new animal.SuitableFood
animal.eat(g) //OK 说明抽象类型成员或类型成员可以作为类的成员即对象的成员,所以路径依赖中的路径是指对象的引用,
// 本例中是animal,有可能引用路径很长,比如animal.dog.chinesedog
}