Is Inheritance really needed?

后端 未结 22 2107
孤街浪徒
孤街浪徒 2020-12-14 00:20

I must confess I\'m somewhat of an OOP skeptic. Bad pedagogical and laboral experiences with object orientation didn\'t help. So I converted into a fervent believer in Visua

22条回答
  •  失恋的感觉
    2020-12-14 01:17

    Inheritance defines an "Is-A" relationship.

    class Point( object ):
        # some set of features: attributes, methods, etc.
    
    class PointWithMass( Point ):
        # An additional feature: mass.
    

    Above, I've used inheritance to formally declare that PointWithMass is a Point.

    There are several ways to handle object P1 being a PointWithMass as well as Point. Here are two.

    1. Have a reference from PointWithMass object p1 to some Point object p1-friend. The p1-friend has the Point attributes. When p1 needs to engage in Point-like behavior, it needs to delegate the work to its friend.

    2. Rely on language inheritance to assure that all features of Point are also applicable to my PointWithMass object, p1. When p1 needs to engage in Point-like behavior, it already is a Point object and can just do what needs to be done.

    I'd rather not manage the extra objects floating around to assure that all superclass features are part of a subclass object. I'd rather have inheritance to be sure that each subclass is an instance of it's own class, plus is an instance of all superclasses, too.

    Edit.

    For statically-typed languages, there's a bonus. When I rely on the language to handle this, a PointWithMass can be used anywhere a Point was expected.

    For really obscure abuse of inheritance, read about C++'s strange "composition through private inheritance" quagmire. See Any sensible examples of creating inheritance without creating subtyping relations? for some further discussion on this. It conflates inheritance and composition; it doesn't seem to add clarity or precision to the resulting code; it only applies to C++.

提交回复
热议问题