Why wont this assignment work?

前端 未结 5 1953
慢半拍i
慢半拍i 2021-01-28 00:04

I\'ve got a class Results which extends ArrayList. I\'ve got an object i which has a function i.getResults() w

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-28 00:18

    You've got the relationship the wrong way round.

    class T {}
    class S extends T {}
    

    The LSP states that:

    in a computer program if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may be substitutes for objects of type T), without altering any of the desirable properties of that program (correctness, task performed, etc.)

    So in other words, anywhere that expects a T can get an S with no problems. Something that wants an S cannot be given a T because it isn't specific enough.

    In your example, i.getResults() returns an ArrayList. You can't assign that to Results because Results is more specific than the array list.

提交回复
热议问题