Why not inherit from List?

前端 未结 27 1714
悲哀的现实
悲哀的现实 2020-11-21 05:39

When planning out my programs, I often start with a chain of thought like so:

A football team is just a list of football players. Therefore, I should

27条回答
  •  一向
    一向 (楼主)
    2020-11-21 05:58

    I just wanted to add that Bertrand Meyer, the inventor of Eiffel and design by contract, would have Team inherit from List without so much as batting an eyelid.

    In his book, Object-Oriented Software Construction, he discusses the implementation of a GUI system where rectangular windows can have child windows. He simply has Window inherit from both Rectangle and Tree to reuse the implementation.

    However, C# is not Eiffel. The latter supports multiple inheritance and renaming of features. In C#, when you subclass, you inherit both the interface and the implemenation. You can override the implementation, but the calling conventions are copied directly from the superclass. In Eiffel, however, you can modify the names of the public methods, so you can rename Add and Remove to Hire and Fire in your Team. If an instance of Team is upcast back to List, the caller will use Add and Remove to modify it, but your virtual methods Hire and Fire will be called.

提交回复
热议问题