I was reading the section 20.7 of the book Programming in Scala and I was wondering why while this code compiles:
class Food
class Fish extends Food
class Gr
Regarding the second part of your question: it doesn't. Animal
doesn't specify that its food is Food
, but some subtype of Food
. Would the compiler accept this, code like your example would compile, and wrongly so. The compiler doesn't know that the necessary subtype is Grass
(which is why eat(new Grass)
doesn't work either), it just knows that there are some foods your cow can't eat and is cautious about it.