HOME

TheInfoList



OR:

In
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
, inheritance is the mechanism of basing an
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ...
or
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differentl ...
upon another object ( prototype-based inheritance) or class ( class-based inheritance), retaining similar
implementation Implementation is the realization of an application, or execution of a plan, idea, model, design, specification, standard, algorithm, or policy. Industry-specific definitions Computer science In computer science, an implementation is a real ...
. Also defined as deriving new classes ( sub classes) from existing ones such as super class or
base class In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object ( prototype-based inheritance) or class ( class-based inheritance), retaining similar implementation. Also defined as deriving new classe ...
and then forming them into a hierarchy of classes. In most class-based object-oriented languages, an object created through inheritance, a "child object", acquires all the properties and behaviors of the "parent object" , with the exception of: constructors, destructor, overloaded operators and
friend function In object-oriented programming, a friend function, that is a "friend" of a given class, is a function that is given the same access as methods to private and protected data. A friend function is declared by the class that is granting access, so ...
s of the base class. Inheritance allows programmers to create classes that are built upon existing classes, to specify a new implementation while maintaining the same behaviors ( realizing an interface), to reuse code and to independently extend original software via public classes and
interface Interface or interfacing may refer to: Academic journals * ''Interface'' (journal), by the Electrochemical Society * '' Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Linguistics'' * '' Int ...
s. The relationships of objects or classes through inheritance give rise to a
directed acyclic graph In mathematics, particularly graph theory, and computer science, a directed acyclic graph (DAG) is a directed graph with no directed cycles. That is, it consists of vertices and edges (also called ''arcs''), with each edge directed from one v ...
. An inherited class is called a subclass of its parent class or super class. The term "inheritance" is loosely used for both class-based and prototype-based programming, but in narrow use the term is reserved for class-based programming (one class ''inherits from'' another), with the corresponding technique in prototype-based programming being instead called '' delegation'' (one object ''delegates to'' another). Class-modifying inheritance patterns can be pre-defined according to simple network interface parameters such that inter-language compatibility is preserved. Inheritance should not be confused with
subtyping In programming language theory, subtyping (also subtype polymorphism or inclusion polymorphism) is a form of type polymorphism in which a subtype is a datatype that is related to another datatype (the supertype) by some notion of substitutability, ...
. In some languages inheritance and subtyping agree, whereas in others they differ; in general, subtyping establishes an
is-a In knowledge representation, object-oriented programming and design (see object-oriented program architecture), is-a (is_a or is a) is a subsumption relationship between abstractions (e.g. types, classes), wherein one class ''A'' is a subclass ...
relationship, whereas 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 sometimes referred to as ''interface inheritance'' (without acknowledging that the specialization of type variables also induces a subtyping relation), whereas inheritance as defined here is known as ''implementation inheritance'' or ''code inheritance''. Still, inheritance is a commonly used mechanism for establishing subtype relationships. Inheritance is contrasted with
object composition In computer science, object composition and object aggregation are closely related ways to combine objects or data types into more complex ones. In conversation the distinction between composition and aggregation is often ignored. Common kind ...
, where one object ''contains'' another object (or objects of one class contain objects of another class); see
composition over inheritance Composition over inheritance (or composite reuse principle) in object-oriented programming (OOP) is the principle that classes should achieve polymorphic behavior and code reuse by their composition (by containing instances of other classes tha ...
. Composition implements a
has-a In database design, object-oriented programming and design (see object oriented program architecture), has-a (has_a or has a) is a composition relationship where one object (often called the constituted object, or part/constituent/member object) " ...
relationship, in contrast to the is-a relationship of subtyping.


History

In 1966,
Tony Hoare Sir Charles Antony Richard Hoare (Tony Hoare or C. A. R. Hoare) (born 11 January 1934) is a British computer scientist who has made foundational contributions to programming languages, algorithms, operating systems, formal verification, and ...
presented some remarks on records, and in particular presented the idea of record subclasses, record types with common properties but discriminated by a variant tag and having fields private to the variant. Influenced by this, in 1967
Ole-Johan Dahl Ole-Johan Dahl (12 October 1931 – 29 June 2002) was a Norwegian computer scientist. Dahl was a professor of computer science at the University of Oslo and is considered to be one of the fathers of Simula and object-oriented programming along w ...
and
Kristen Nygaard Kristen Nygaard (27 August 1926 – 10 August 2002) was a Norwegian computer scientist, programming language pioneer, and politician. Internationally, Nygaard is acknowledged as the co-inventor of object-oriented programming and the programming ...
presented a design that allowed specifying objects that belonged to different classes but had common properties. The common properties were collected in a superclass, and each superclass could itself potentially have a superclass. The values of a subclass were thus compound objects, consisting of some number of prefix parts belonging to various superclasses, plus a main part belonging to the subclass. These parts were all concatenated together. The attributes of a compound object would be accessible by dot notation. This idea was first adopted in the Simula 67 programming language. The idea then spread to Smalltalk,
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
,
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mos ...
,
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
, and many other languages.


Types

There are various types of inheritance, based on paradigm and specific language. ;Single inheritance :where subclasses inherit the features of one superclass. A class acquires the properties of another class. ;Multiple inheritance :where one class can have more than one superclass and inherit features from all parent classes. : ;Multilevel inheritance :where a subclass is inherited from another subclass. It is not uncommon that a class is derived from another derived class as shown in the figure "Multilevel inheritance". : :The class ''A'' serves as a ''base class'' for the ''derived class'' ''B'', which in turn serves as a ''base class'' for the ''derived class'' ''C''. The class ''B'' is known as ''intermediate'' base class because it provides a link for the inheritance between ''A'' and ''C''. The chain ''ABC'' is known as ''inheritance path''. :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. ;Hierarchical inheritance :This is where one class serves as a superclass (base class) for more than one sub class. For example, a parent class, A, can have two subclasses B and C. Both B and C's parent class is A, but B and C are two separate subclasses. ;Hybrid inheritance :Hybrid inheritance is when a mix of two or more of the above types of inheritance occurs. An example of this is when class A has a subclass B which has two subclasses, C and D. This is a mixture of both multilevel inheritance and hierarchal inheritance.


Subclasses and superclasses

''Subclasses'', ''derived classes'', ''heir classes'', or ''child classes'' are
modular Broadly speaking, modularity is the degree to which a system's components may be separated and recombined, often with the benefit of flexibility and variety in use. The concept of modularity is used primarily to reduce complexity by breaking a s ...
derivative classes that inherits one or more
language Language is a structured system of communication. The structure of a language is its grammar and the free components are its vocabulary. Languages are the primary means by which humans communicate, and may be conveyed through a variety of ...
entities from one or more other classes (called ''superclass'', ''base classes'', or ''parent classes''). The semantics of class inheritance vary from language to language, but commonly the subclass automatically inherits the
instance variable In class-based, object-oriented programming, an instance variable is a variable defined in a class (i.e. a member variable), for which each instantiated object of the class has a separate copy, or instance. An instance variable has similariti ...
s and
member function A method in object-oriented programming (OOP) is a procedure associated with a message and an object. An object consists of ''state data'' and ''behavior''; these compose an ''interface'', which specifies how the object may be utilized by any of ...
s of its superclasses. The general form of defining a derived class is: class SubClass: visibility SuperClass ; * The colon indicates that the subclass inherits from the superclass. The visibility is optional and, if present, may be either ''private'' or ''public''. The default visibility is ''private''. Visibility specifies whether the features of the base class are ''privately derived'' or ''publicly derived''. Some languages support also the inheritance of other constructs. For example, in
Eiffel Eiffel may refer to: Places * Eiffel Peak, a summit in Alberta, Canada * Champ de Mars – Tour Eiffel station, Paris, France; a transit station Structures * Eiffel Tower, in Paris, France, designed by Gustave Eiffel * Eiffel Bridge, Ungheni, M ...
, contracts that 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 In computer science, compile time (or compile-time) describes the time window during which a computer program is compiled. The term is used as an adjective to describe concepts related to the context of program compilation, as opposed to concept ...
. A uniform interface is used to invoke the member functions of objects of a number of different classes. Subclasses may replace superclass functions with entirely new functions that must share the same method signature.


Non-subclassable classes

In some languages a class may be declared as non-subclassable by adding certain class modifiers to the class declaration. Examples include the final keyword in
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mos ...
and
C++11 C++11 is a version of the ISO/ IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions b ...
onwards or the sealed keyword in C#. Such modifiers are added to the class declaration before the class keyword and the class identifier declaration. Such non-subclassable classes restrict
reusability In computer science and software engineering, reusability is the use of existing ''assets'' in some form within the software product development process; these ''assets'' are products and by-products of the software development life cycle and in ...
, particularly when developers only have access to precompiled
binaries A binary file is a computer file that is not a text file. The term "binary file" is often used as a term meaning "non-text file". Many binary file formats contain parts that can be interpreted as text; for example, some computer document fil ...
and not
source code In computing, source code, or simply code, is any collection of code, with or without comments, written using a human-readable programming language, usually as plain text. The source code of a program is specially designed to facilitate the w ...
. A non-subclassable class has no subclasses, so it can be easily deduced at
compile time In computer science, compile time (or compile-time) describes the time window during which a computer program is compiled. The term is used as an adjective to describe concepts related to the context of program compilation, as opposed to concep ...
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 In computer science, type conversion, type casting, type coercion, and type juggling are different ways of changing an expression from one data type to another. An example would be the conversion of an integer value into a floating point valu ...
a reference type violates the type system). Because the exact type of the object being referenced is known before execution,
early binding In object-oriented programming, inheritance is the mechanism of basing an Object (computer science), object or Class (computer programming), class upon another object (Prototype-based programming, prototype-based inheritance) or class (Class-based ...
(also called static dispatch) can be used instead of
late binding In computing, late binding or dynamic linkage—though not an identical process to dynamically linking imported code libraries—is a computer programming mechanism in which the method being called upon an object, or the function being called ...
(also called
dynamic dispatch In computer science, dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at run time. It is commonly employed in, and considered a prime characteristic of, object-oriented ...
), which requires one or more
virtual method table In computer programming, a virtual method table (VMT), virtual function table, virtual call table, dispatch table, vtable, or vftable is a mechanism used in a programming language to support dynamic dispatch (or run-time method binding). Whe ...
lookups depending on whether
multiple inheritance Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class. It is distinct from single inheritance, where an object or ...
or only
single inheritance Multiple inheritance is a feature of some object-oriented programming, object-oriented computer programming languages in which an object or class (computer programming), class can inheritance (object-oriented programming), inherit features from mor ...
are supported in the programming language that is being used.


Non-overridable methods

Just as classes may be non-subclassable, 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 Private or privates may refer to: Music * " In Private", by Dusty Springfield from the 1990 album ''Reputation'' * Private (band), a Denmark-based band * "Private" (Ryōko Hirosue song), from the 1999 album ''Private'', written and also recorde ...
method is un-overridable 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 In object-oriented programming, in languages such as C++, and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated. This concept is an important part ...
, then invocations of the superclass method will be dynamically dispatched. Some languages require that methods 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 optimizations such as
inline expansion In computing, inline expansion, or inlining, is a manual or compiler optimization that replaces a function call site with the body of the called function. Inline expansion is similar to macro expansion, but occurs during compilation, without cha ...
.


Visibility of inherited members

The following table shows which variables and functions get inherited dependent on the visibility given when deriving the class, using the terminology established by C++.


Applications

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


Overriding

Many
object-oriented programming languages Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of p ...
permit a class or object to replace the implementation of an aspect—typically a behavior—that it has inherited. This process is called '' overriding''. Overriding introduces a complication: which version of the behavior does an instance of the inherited class use—the 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, while in programming languages such as Java, different methods can be called to override other methods. An alternative to overriding is hiding the inherited code.


Code reuse

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 Override may refer to: * Dr. Gregory Herd, a Marvel Comics character formerly named Override * Manual override, a function where an automated system is placed under manual control * Method overriding, a subclassing feature in Object Oriented progr ...
some or all operations, replacing the base-class implementation with its own. In the following Python example, subclasses and override the method of the base class . The base class comprises operations to compute the sum of the
squares In Euclidean geometry, a square is a regular quadrilateral, which means that it has four equal sides and four equal angles (90- degree angles, π/2 radian angles, or right angles). It can also be defined as a rectangle with two equal-length a ...
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
square In Euclidean geometry, a square is a regular quadrilateral, which means that it has four equal sides and four equal angles (90- degree angles, π/2 radian angles, or right angles). It can also be defined as a rectangle with two equal-length a ...
and cube respectively. The subclasses therefore compute the sum of the squares/cubes between two integers. Below is an example of Python. class SumComputer: def __init__(self, a, b): self.a = a self.b = b def transform(self, x): raise NotImplementedError def inputs(self): return range(self.a, self.b) def compute(self): return sum(self.transform(value) for value in self.inputs()) class SquareSumComputer(SumComputer): def transform(self, x): return x * x class CubeSumComputer(SumComputer): 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, explicit delegation, requires more programming effort, but avoids the substitutability issue. In C++ private inheritance can be used as a 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. Another frequent use of inheritance is to guarantee that classes maintain a certain common interface; that is, they implement the same methods. The parent class can be a combination of implemented operations and operations that are to be implemented in the child classes. Often, there is no interface change between the supertype and subtype- the child implements the behavior described instead of its parent class.


Inheritance vs subtyping

Inheritance is similar to but distinct from subtyping. 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 ; class B : public A ; void UseAnA(const A& a) void SomeFunc() 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 Type may refer to: Science and technology Computing * Typing, producing text via a keyboard, typewriter, etc. * Data type In computer science and computer programming, a data type (or simply type) is a set of possible values and a set of allo ...
. Inheritance, even in programming languages that support inheritance as a subtyping mechanism, does not necessarily entail
behavioral subtyping In object-oriented programming, behavioral subtyping is the principle that subclasses should satisfy the expectations of clients accessing subclass objects through references of superclass type, not just as regards syntactic safety (such as the abse ...
. 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.


Design constraints

Using inheritance extensively in designing a program imposes certain constraints. For example, consider a class that contains a person's name, date of birth, address and phone number. We can define a subclass of called that contains the person's grade point average and classes taken, and another subclass of called 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: ;Singleness: Using single inheritance, a subclass can inherit from only one superclass. Continuing the example given above, a object can be either a or an , but not both. Using multiple inheritance partially solves this problem, as one can then define a class that inherits from both and . However, in most implementations, it can still inherit from each superclass only once, and thus, does not support cases in which a student has two jobs or attends two institutions. The inheritance model available in Eiffel makes this possible through support for repeated inheritance. ;Static: The inheritance hierarchy of an object is fixed at instantiation when the object's type is selected and does not change with time. For example, the inheritance graph does not allow a object to become a object while retaining the state of its superclass. (This kind of behavior, however, can be achieved with the
decorator pattern In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class. The decorator pattern is often ...
.) Some have criticized inheritance, contending that it locks developers into their original design standards. ;Visibility: Whenever client code has access to an object, it generally has access to all the object's superclass data. Even if the superclass has not been declared public, the client can still
cast Cast may refer to: Music * Cast (band), an English alternative rock band * Cast (Mexican band), a progressive Mexican rock band * The Cast, a Scottish musical duo: Mairi Campbell and Dave Francis * ''Cast'', a 2012 album by Trespassers William ...
the object to its superclass type. For example, there is no way to give a function a pointer to a 's grade point average and transcript without also giving that function access to all of the personal data stored in the student's superclass. Many modern languages, including C++ and Java, provide a "protected" access modifier that allows subclasses to access the data, without allowing any code outside the chain of inheritance to access it. 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 one 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. For example, the decorator pattern (as mentioned above) has been proposed to overcome the static nature of inheritance between classes. As a more fundamental solution to the same problem,
role-oriented programming Role-oriented programming as a form of computer programming aims at expressing things in terms that are analogous to human conceptual understanding of the world. This should make programs easier to understand and maintain. The main idea of rol ...
introduces a distinct relationship, ''played-by'', combining properties of inheritance and composition into a new concept. According to
Allen Holub Allen, Allen's or Allens may refer to: Buildings * Allen Arena, an indoor arena at Lipscomb University in Nashville, Tennessee * Allen Center, a skyscraper complex in downtown Houston, Texas * Allen Fieldhouse, an indoor sports arena on the Univer ...
, the main problem with implementation inheritance is that it introduces unnecessary
coupling A coupling is a device used to connect two shafts together at their ends for the purpose of transmitting power. The primary purpose of couplings is to join two pieces of rotating equipment while permitting some degree of misalignment or end mov ...
in the form of the "fragile base class problem": modifications to the base class implementation can cause inadvertent behavioral changes in subclasses. Using interfaces avoids this problem because no implementation is shared, only the API. Another way of stating this is that "inheritance breaks encapsulation". The problem surfaces clearly in open object-oriented systems such as
frameworks A framework is a generic term commonly referring to an essential supporting structure which other things are built on top of. Framework may refer to: Computing * Application framework, used to implement the structure of an application for an op ...
, where client code is expected to inherit from system-supplied classes and then substituted for the system's classes in its algorithms. Reportedly, Java inventor
James Gosling James Gosling (born May 19, 1955) is a Canadian computer scientist, best known as the founder and lead designer behind the Java programming language. Gosling was elected a member of the National Academy of Engineering in 2004 for the conception ...
has spoken against implementation inheritance, stating that he would not include it if he were to redesign Java. Language designs that decouple inheritance from subtyping (interface inheritance) appeared as early as 1990; 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. When inheritance was used as a primary approach to structure programs in the late 1990s, developers tended to break code into more layers of inheritance as the system functionality grew. If a development team combined multiple layers of inheritance with the single responsibility principle, this resulted in many very thin layers of code, with many layers consisting of only 1 or 2 lines of actual code. Too many layers make debugging a significant challenge, as it becomes hard to determine which layer needs to be debugged. Another issue with inheritance is that subclasses must be defined in code, which means that program users cannot add new subclasses at runtime. Other design patterns (such as
Entity–component–system Entity Component System (ECS) is a software architectural pattern mostly used in video game development for the representation of game world objects. An ECS comprises ''entities'' composed from ''components'' of data, with ''systems'' which opera ...
) allow program users to define variations of an entity at runtime.


See also

* * * * * * * * * * * *


Notes


References


Further reading

* * {{Authority control Object-oriented programming Type systems Articles with example Python (programming language) code