When is it Appropriate to use Generics Versus Inheritance?

前端 未结 7 733
傲寒
傲寒 2020-12-16 00:12

What are the situations and their associated benefits of using Generics over Inheritance and vice-versa, and how should they be best combined?

Thanks for the answer

7条回答
  •  误落风尘
    2020-12-16 01:01

    Use generics when you want to create a "template" that can apply to many styles of unknown classes. Eg. Collections holding ??? are good candidates for generics. Inheritance is for when you have a base conecpt that children "are" an extension of that concept.

    My general rules

    • if you start defining properites as Object in your code and type casting a lot, then its probably time for generics.
    • If you want to program against the "higher concept" as well as the derived class then its inheritance.
    • If your class is going to wrap or work on a concerte class then its generics.
    • If you are relying on the specifics of an unknown "yet to be defined" class then your probably better with generics.
    • If you derived classes are "is a" then its usually inheritance
    • If your superclass "uses some x" then its generics.

提交回复
热议问题