How do I make the method return type generic?

前端 未结 19 2404
無奈伤痛
無奈伤痛 2020-11-22 06:16

Consider this example (typical in OOP books):

I have an Animal class, where each Animal can have many friends.
And subclasses like

19条回答
  •  清酒与你
    2020-11-22 06:27

    Not possible. How is the Map supposed to know which subclass of Animal it's going to get, given only a String key?

    The only way this would be possible is if each Animal accepted only one type of friend (then it could be a parameter of the Animal class), or of the callFriend() method got a type parameter. But it really looks like you're missing the point of inheritance: it's that you can only treat subclasses uniformly when using exclusively the superclass methods.

提交回复
热议问题