When should I use generics to define relationships between types?

前端 未结 6 1353
隐瞒了意图╮
隐瞒了意图╮ 2020-12-08 21:50

Getting into a little bit of confusion here when to use generics. I\'ve looked at Java Generics? but still have a few questions.

Say I have:

public          


        
6条回答
  •  囚心锁ツ
    2020-12-08 22:03

    I'd suggest to focus on semantics first:

    Providing that you may have a Bmw and a Toyota classes implementing the ICar interface, then make this question: can a Person change his car or would it be a different person if he does so?

    The generics approach will force you to create a new Person instance if for some reason you need to change the value of the car attribute from Toyota to Bmw in an existent person instance and thus, this new person will be different from the previous one. Of course, you could create the first Person instance as Person instead of hooking it to a specific car class but, why use generics then?

提交回复
热议问题