简体   繁体   中英

Am I correct to think of inheritance as a combination of these 3 things?

A inherits B means

  1. A owns B.
  2. A shares all B interface.
  3. A shares implementation of B interface.

Abstract classes are similar (@protocol in objective-c, for example.

A implements B means 2. A shares all B interface.

As for A owns B and A shares implementation of B, I see that as something that can be "pushed" with combination of @protocol and category.

In any case, that's all inheritance is all about right?

  1. Ownership
  2. Sharing interface
  3. Sharing implementation.

If I am wrong in any of these, would anyone please correct me.

Ownership

Yes, that's essentially correct. Some might quibble about the "ownership" claim. That might suggest that B "has a" A rather than B "is an" A. In object-oriented lingo, a has-a relationship generally implies that one of B's fields is a pointer to an A object. An is-a relationship implies that part of B's memory contains an A object. With common object-oriented languages, inheritance implies an is-a relationship, not a has-a relationship.

Consider these two sketches

B has-a A
=========

        +--------------+    +----------------+
B* b -> | A* a_part    | -> | float a_field1 |
        | int b_field1 |    | float a_field2 |
        | int b_field2 |    +----------------+
        +--------------+

B is-a A
========

        +----------------+
B* b -> | float a_field1 | <- A* a_part_of_b
        | float a_field2 |
        | int   b_field1 |
        | int   b_field2 |
        +----------------+

Another important property of an is-a relationship is that a pointer to the subclass can be safely treated as a pointer to the superclass. This doesn't normally work with has-a relationships without a conversion or extraction method being employed.

The concept of 'ownership' here is maybe problematic. I think the most simple way to put it is that 'A', when inheriting from 'B', does everything that 'B' does, except for when 'A' decides to do something different. 'A' has no ownership of 'B', other than that by default it acts as 'B' until you tell it to do something different.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM