When should I use generics to define relationships between types?

前端 未结 6 1366
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  旧时难觅i
    2020-12-08 22:18

    You need the generics version if you have any methods that take or return anything involving a T, or if it's possible for other people to access your car field. (Since you didn't show any methods, we can't really tell.)

    For example, with the generics version you can have a method like T someMethod();, then when someone has a Person, they know they can get a Honda back when they call someMethod, rather than some unknown type of car if you didn't have generics.

    Similarly, with the generics version you can have a method like void anotherMethod(T anotherCar);, then when someone has a Person, this forces them to pass a Honda to this method, instead of any car.

    So basically, having a generic class allows you to place constraints on uses of the object later on (method calls etc.). If the constructor is the only place that you use T, and you don't need to use T in any methods or fields, then yes, there is no point for it.

提交回复
热议问题