Why wont this assignment work?

前端 未结 5 1946
慢半拍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条回答
  • 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<Results>. You can't assign that to Results because Results is more specific than the array list.

    0 讨论(0)
  • 2021-01-28 00:18

    Well, you're trying to assign an object of a superclass type to a reference of a subclass type, and of course that's a compile-time error, because it might not be valid. It's the same as if you tried to assign the return value of a method that returns Object to a variable of type String. If you are absolutely sure the getResults() method returns a Results object, you should change its return type. Or if you're only sure of it in this context, you can use a cast.

    0 讨论(0)
  • 2021-01-28 00:20

    You can't - ArrayList<Results> isn't a Results. Results is an ArrayList<Results> though, you could assign the other way.

    0 讨论(0)
  • 2021-01-28 00:27

    You have

      Results extends ArrayList<Results>
    

    So anywhere you might use ArrayList you can use Results, but not vice-versa. When you say extends you are saying I can do everything he can do, and a little bit more.

      C extends D
    

    says: if all you need is a D then you can use either a C or a D. But someone needing a C cannot accept a D, because it doesn have all the capabilities C offers.

    0 讨论(0)
  • 2021-01-28 00:31

    You're assigning a parent to the child class. This is not possible. You can assign do

    ArrayList<Result> list = new Results();
    
    0 讨论(0)
提交回复
热议问题