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:

    As to honour—you know—it’s a very fine mediaeval inheritance which women never got hold of. It wasn’t theirs.
    Joseph Conrad (1857–1924)