Inheritance (object-oriented Programming) - Inheritance Vs Subtyping

Inheritance Vs Subtyping

Subtyping enables a given type to be substituted for another type or abstraction. Subtyping is said to establish an is-a relationship between the subtype and some existing abstraction, either implicitly or explicitly, depending on language support. The relationship can be expressed explicitly via inheritance in languages that support inheritance as a subtyping mechanism. For example, the following C++ code establishes an explicit inheritance relationship between classes B and A, where B is both a subclass and a subtype of A, and can be used as an A wherever a B is specified (via a reference, a pointer or the object itself).

class A { public: void DoSomethingALike const {} }; class B : public A { public: void DoSomethingBLike const {} }; void UseAnA(A const& some_A) { some_A.DoSomethingALike; } void SomeFunc { B b; UseAnA(b); // b can be substituted for an A. }

In programming languages that do not support inheritance as a subtyping mechanism, the relationship between a base class and a derived class is only a relationship between implementations (a mechanism for code reuse), as compared to a relationship between types. Inheritance, even in programming languages that support inheritance as a subtyping mechanism, does not necessarily entail behavioral subtyping. It is entirely possible to derive a class whose object will behave incorrectly when used in a context where the parent class is expected; see the Liskov substitution principle. (Compare connotation/denotation.) In some OOP languages, the notions of code reuse and subtyping coincide because the only way to declare a subtype is to define a new class that inherits the implementation of another.

Read more about this topic:  Inheritance (object-oriented Programming)

Famous quotes containing the word inheritance:

    I call it our collective inheritance of isolation. We inherit isolation in the bones of our lives. It is passed on to us as sure as the shape of our noses and the length of our legs. When we are young, we are taught to keep to ourselves for reasons we may not yet understand. As we grow up we become the “men who never cry” and the “women who never complain.” We become another generation of people expected not to bother others with our problems.
    Paula C. Lowe (20th century)