Inheritance (object-oriented programming)

In object-oriented programming (OOP), inheritance is when an object or class is based on another object or class, using the same implementation (inheriting from a class) specifying implementation to maintain the same behavior (realizing an interface; inheriting behavior). It is a mechanism for code reuse and to allow independent extensions of the original software via public classes and interfaces. The relationships of objects or classes through inheritance give rise to a hierarchy. Inheritance was invented in 1967 for Simula.[1]

Inheritance should not be confused with subtyping.[2][3] In some languages inheritance and subtyping agree,[lower-alpha 1] while in others they differ; in general subtyping establishes an is-a relationship, while inheritance only reuses implementation and establishes a syntactic relationship, not necessarily a semantic relationship (inheritance does not ensure behavioral subtyping). To distinguish these concepts, subtyping is also known as interface inheritance, while inheritance as defined here is known as implementation inheritance or code inheritance.[4]

Inheritance is contrasted with object composition, where one object contains another object (or objects of one class contain objects of another class); see composition over inheritance. Composition implements a has-a relationship, in contrast to the is-a relationship of subtyping.

Types of inheritance

There are various types of inheritance,[5] based on paradigm and specific language.

"Multiple Inheritance (object-oriented programming) was widely supposed to be very difficult to implement efficiently. For example, in a summary of C++ in his book on objective C Brd.Cox actually claimed that adding Multiple inheritance to C++ was impossible. Thus, multiple inheritance seemed more of a challenge. Since I had considered multiple inheritance as early as 1982 and found a simple and efficient implementation technique in 1984. I couldn't resist the challenge. I suspect this to be the only case in which fashion affected the sequence of events."[6]

Bjarne Stroustrup

A derived class with multilevel inheritance is declared as follows:

Class A(...);      //Base class
Class B : public A(...);   //B derived from A
Class C : public B(...);   //C derived from B

This process can be extended to any number of levels.

Subclasses and superclasses

A Subclass, "derived class", heir class, or child class is a modular, derivative class that inherits one or more language entities from one or more other classes (called superclasses, base classes, or parent classes). The semantics of class inheritance vary from language to language, but commonly the subclass automatically inherits the instance variables and member functions of its superclasses. The general form of defining a derived class is:

class derived-class-name : visibility-mode base-class-name
{
 .....//
 .....// members of derived class
 .....//
};

[7]

Some languages support the inheritance of other construct as well. For example, in Eiffel, contracts which define the specification of a class are also inherited by heirs. The superclass establishes a common interface and foundational functionality, which specialized subclasses can inherit, modify, and supplement. The software inherited by a subclass is considered reused in the subclass. A reference to an instance of a class may actually be referring to one of its subclasses. The actual class of the object being referenced is impossible to predict at compile-time. A uniform interface is used to invoke the member functions of objects of a number of different classes. Subclass may replace superclass functions with entirely new functions that must share the same method signature.

Uninheritable classes

In some languages a class may be declared as uninheritable by adding certain class modifiers to the class declaration. Examples include the "final" keyword in Java or the "sealed" keyword in C#. Such modifiers are added to the class declaration before the "class" keyword and the class identifier declaration. Such sealed classes restrict reusability, particularly when developers only have access to precompiled binaries and not source code.

The sealed class has no subclasses, so it can be easily deduced at compile time that references or pointers to objects of that class are actually referencing instances of that class and not instances of subclasses (they don't exist) or instances of superclasses (upcasting a reference type violates the type system). subtype polymorphism. Because the exact type of the object being referenced is known before execution, early binding (or "static dispatch") can be used instead of late binding (also called "dynamic dispatch" or "dynamic binding") which requires one or more virtual method table lookups depending on whether multiple inheritance or only single inheritance are supported in the programming language that is being used.

Methods that cannot be overridden

Just as classes may be sealed/finalized method declarations may contain method modifiers that prevent the method from being overridden (i.e. replaced with a new function with the same name and type signature in a subclass). A private method is unoverridable simply because it is not accessible by classes other than the class it is a member function of (this is not true for C++, though). A "final" method in Java, a "sealed" method in C# or a frozen feature in Eiffel cannot be overridden.

Virtual methods

If the superclass method is a virtual method, then invocations of the superclass method will be dynamically dispatched. Some languages require methods to be specifically declared as virtual (e.g. C++) and in others all methods are virtual (e.g. Java). An invocation of a non-virtual method will always be statically dispatched (i.e. the address of the function call is determined at compile-time). Static dispatch is faster than dynamic dispatch and allows optimisations such as inline expansion.

Visibility of Inherited Members

Base class visibility Derived Class visibility
Public Derivation Private Derivation Protected Derivation
  • Private →
  • Protected →
  • Public →
  • Not inherited
  • Protected
  • Public
  • Not inherited
  • Private
  • Private
  • Not inherited
  • Protected
  • Protected

[8]

Applications

Inheritance is used to co-relate two or more classes to each other.

Many object-oriented programming languages permit a class or object to replace the implementation of an aspecttypically a behaviorthat it has inherited. This process is usually called overriding. Overriding introduces a complication: which version of the behavior does an instance of the inherited class usethe one that is part of its own class, or the one from the parent (base) class? The answer varies between programming languages, and some languages provide the ability to indicate that a particular behavior is not to be overridden and should behave as defined by the base class. For instance, in C#, the base method or property can only be overridden in a subclass if it is marked with the virtual, abstract, or override modifier.[9] An alternative to overriding is hiding the inherited code.

Implementation inheritance is the mechanism whereby a subclass re-uses code in a base class. By default the subclass retains all of the operations of the base class, but the subclass may override some or all operations, replacing the base-class implementation with its own.

In the following Python example, the subclass CubeSumComputer overrides the transform() method of the base class SquareSumComputer. The base class comprises operations to compute the sum of the squares between two integers. The subclass re-uses all of the functionality of the base class with the exception of the operation that transforms a number into its square, replacing it with an operation that transforms a number into its cube. The subclass therefore computes the sum of the cubes between two integers.

class SquareSumComputer(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b
 
    def transform(self, x):
        return x * x
 
    def inputs(self):
        return range(self.a, self.b)
 
    def compute(self):
        return sum(self.transform(value) for value in self.inputs())
 
class CubeSumComputer(SquareSumComputer):
    def transform(self, x):
        return x * x * x

In most quarters, class inheritance for the sole purpose of code reuse has fallen out of favor. The primary concern is that implementation inheritance does not provide any assurance of polymorphic substitutability—an instance of the reusing class cannot necessarily be substituted for an instance of the inherited class. An alternative technique, delegation, requires more programming effort, but avoids the substitutability issue. In C++ private inheritance can be used as form of implementation inheritance without substitutability. Whereas public inheritance represents an "is-a" relationship and delegation represents a "has-a" relationship, private (and protected) inheritance can be thought of as an "is implemented in terms of" relationship.[10]

Inheritance vs subtyping

Further information: Subtyping

Inheritance is similar to but distinct from subtyping.[12] Subtyping enables a given type to be substituted for another type or abstraction, and 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. [13] (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.

Design constraints

Using inheritance extensively in designing a program imposes certain constraints.

For example, consider a class Person that contains a person's name, date of birth, address and phone number. We can define a subclass of Person called Student that contains the person's grade point average and classes taken, and another subclass of Person called Employee that contains the person's job-title, employer, and salary.

In defining this inheritance hierarchy we have already defined certain restrictions, not all of which are desirable:

The composite reuse principle is an alternative to inheritance. This technique supports polymorphism and code reuse by separating behaviors from the primary class hierarchy and including specific behavior classes as required in any business domain class. This approach avoids the static nature of a class hierarchy by allowing behavior modifications at run time and allows a single class to implement behaviors buffet-style, instead of being restricted to the behaviors of its ancestor classes.

Issues and alternatives

Implementation inheritance is controversial among programmers and theoreticians of object-oriented programming since at least the 1990s. Among them are the authors of Design Patterns, who advocate interface inheritance instead, and favor composition over inheritance.[14]

According to Allen Holub, the main problem with implementation inheritance is that it introduces unnecessary coupling in the form of the "fragile base class problem":[4] modifications to the base class implementation can cause inadvertent behavioral changes in subclasses. Using interfaces avoids this problem since no implementation is shared, only the API.[14] Another way of stating this is that "inheritance breaks encapsulation".[15] The problem surfaces clearly in open object-oriented systems such as frameworks, where client code is expected to inherit from system-supplied classes and then substituted for the system's classes in its algorithms.[4]

Reportedly, Java inventor James Gosling has spoken against implementation inheritance, stating that he would not include it if he were to redesign Java.[14] Language designs that decouple inheritance from subtyping (interface inheritance) appeared as early as 1990;[16] a modern example of this is the Go programming language.

Complex inheritance, or inheritance used within an insufficiently mature design, may lead to the yo-yo problem.

See also

Notes

  1. This is generally true only in statically-typed class-based OO languages, such as Java, C#, C++ and Scala.

References

  1. Mike Mintz, Robert Ekendahl (2006). Hardware Verification with C++: A Practitioner’s Handbook. United States of America: Springer. p. 22. ISBN 0-387-25543-5.
  2. Cook, William R.; Hill, Walter; Canning, Peter S. (1990). Inheritance is not subtyping. Proc. 17th ACM SIGPLAN-SIGACT Symp. on Principles of Programming Languages (POPL). pp. 125–135. doi:10.1145/96709.96721. ISBN 0-89791-343-4. CiteSeerX: 10.1.1.102.8635.
  3. Cardelli, Luca (1993). Typeful Programming (Technical report). Digital Equipment Corporation. p. 32–33. SRC Research Report 45.
  4. 4.0 4.1 4.2 Mikhajlov, Leonid; Sekerinski, Emil (1998). A study of the fragile base class problem (PDF). Proc. 12th European Conf. on Object-Oriented Programming (ECOOP). Lecture Notes in Computer Science 1445. pp. 355–382. doi:10.1007/BFb0054099. ISBN 978-3-540-64737-9.
  5. "Inheritance in C++".
  6. Bjarne Stroustrup. The Design and Evolution of C++. p. 417.
  7. Herbert Schildt (2003). The complete reference C++. Tata McGrawhill Education Private Limited. p. 417. ISBN 0-07-053246-X.
  8. E Balagurusamy (2010). Object Orientedprogramming With C++. Tata McGrawhill Education Pvt. Ltd. p. 213. ISBN 0-07-066907-4.
  9. http://msdn.microsoft.com/en-us/library/ebca9ah3.aspx override(C# Reference)
  10. "GotW #60: Exception-Safe Class Design, Part 2: Inheritance". Gotw.ca. Retrieved 2012-08-15.
  11. Dr. K. R. Venugopal, Rajkumar Buyya (2013). Mastering C++. Tata McGrawhill Education Private Limited. p. 609. ISBN 9781259029943.
  12. Cook, Hill & Canning 1990.
  13. Mitchell, John (2002). "10 "Concepts in object-oriented languages"". Concepts in programming language. Cambridge, UK: Cambridge University Press. p. 287. ISBN 0-521-78098-5.
  14. 14.0 14.1 14.2 14.3 Holub, Allen (1 August 2003). "Why extends is evil". Retrieved 10 March 2015.
  15. Seiter, Linda M.; Palsberg, Jens; Lieberherr, Karl J. (1996). "Evolution of object behavior using context relations". ACM SIGSOFT Software Engineering Notes 21 (6): 46. doi:10.1145/250707.239108. CiteSeerX: 10.1.1.36.5053.
  16. America, Pierre (1991). Designing an object-oriented programming language with behavioural subtyping (PDF). REX School/Workshop on the Foundations of Object-Oriented Languages. Lecture Notes in Computer Science 489. pp. 60–90. doi:10.1007/BFb0019440. ISBN 978-3-540-53931-5.

Further reading