SOLFIND
Web Lens
Portal home

Inheritance (object-oriented programming) - Wikipedia

https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) • 239 KB fetched
Open original page


Inheritance (object-oriented programming) - Wikipedia

*

Home

*

Random

*

Nearby

*

Create account

*

Log in

*

Settings

Donate Now
If Wikipedia is useful to you, please give today.

*

About Wikipedia

*

Disclaimers

Search

User menu

*

Create account

*

Log in

Inheritance (object-oriented programming)

*
Article

*
Talk

*

Language

*

Watch

*

Edit

"Classical inheritance" redirects here. For later inheritance of ancient culture, see classical tradition .

{{cite web|url=https://www.cse.msu.edu/~cse870/Input/SS2002/MiniProject/Sources/DRC.pdf |title=Designing Reusable Classes |last=Johnson |first=Ralph |date=August 26, 1991 |website=www.cse.msu.edu }}</ref> to specify a new implementation while maintaining the same behaviors ([[Class diagram#Realization/Implementation|realizing an interface]]), to reuse code and to independently extend original software via public classes and [[interface (object-oriented programming)|interface]]s. The relationships of objects or classes through inheritance give rise to a [[directed acyclic graph]]."]}"> This article may require cleanup to meet Wikipedia's quality standards . The specific problem is: Cluttered. Please help improve this article if you can. ( April 2015 ) ( Learn how and when to remove this message )

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 . It is also defined as deriving new classes ( sub classes ) from existing ones such as super class or base class and then forming them into a hierarchy of classes. In most class-based object-oriented languages like C++ , an object created through inheritance, a "child object", acquires all the properties and behaviors of the "parent object", with the exception of: constructors , destructors, overloaded operators and friend functions of the base class. Inheritance allows programmers to create classes that are built upon existing classes, [ 1 ] 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 interfaces . The relationships of objects or classes through inheritance give rise to a directed acyclic graph .

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. [ 2 ] [ 3 ]

Inheritance should not be confused with subtyping . [ 4 ] [ 5 ] In some languages, generally statically-typed class-based OO languages, like C++ , C# , Java, and Scala , inheritance and subtyping agree, whereas in others they differ. In general, subtyping establishes an is-a 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 . [ 6 ] Still, inheritance is a commonly used mechanism for establishing subtype relationships. [ 7 ]

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 . In contrast to subtyping's is-a relationship, composition implements a has-a relationship.

Mathematically speaking, inheritance in any system of classes induces a strict partial order on the set of classes in that system.

Contents

* 1 History

* 2 Types

* 3 Subclasses and superclasses
* 3.1 Non-subclassable classes

* 3.2 Non-overridable methods

* 3.3 Virtual methods

* 4 Visibility of inherited members

* 5 Applications
* 5.1 Overriding

* 5.2 Code reuse

* 6 Inheritance vs subtyping
* 6.1 Design constraints

* 7 Issues and alternatives

* 8 See also

* 9 References

* 10 Further reading

History

edit

In 1966, Tony Hoare presented some remarks on records, and in particular, the idea of record subclasses, record types with common properties but discriminated by a variant tag and having fields private to the variant. [ 8 ] Influenced by this, in 1967 Ole-Johan Dahl and Kristen Nygaard 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. [ 9 ] The attributes of a compound object would be accessible by dot notation. This idea was first adopted in the Simula 67 programming language. [ 10 ] The idea then spread to Smalltalk , C++ , Java , Python , and many other languages.

Types

edit

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

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.
"Multiple inheritance   ... was widely supposed to be very difficult to implement efficiently. For example, in a summary of C++ in his book on Objective C , Brad 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." [ 12 ]

—   Bjarne Stroustrup

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".
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:
// C++ language implementation
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 a 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

edit

Subclasses , derived classes , heir classes , or child classes are modular derivative classes that inherit one or more language 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 variables and member functions of its superclasses.

In C++, the general form of defining a derived class is: [ 13 ]

class SubClass : visibility SuperClass {
// subclass members
};

The colon indicates that the subclass inherits from the superclass. The visibility modifier is optional and, if present, may be either private or public . The default visibility (if there is no modifier present) is private . Visibility specifies whether the features of the base class are privately derived or publicly derived .

Note that in some other languages like Java and C#, there is no visibility modifier for inheritance:

// No visibility modifier
// Equivalent to public SuperClass in C++
class SubClass extends SuperClass {
// subclass members
}

Some languages also support the inheritance of other constructs. For example, in Eiffel , 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 . 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

edit

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 and C++11 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 , particularly when developers only have access to precompiled binaries and not source code .

A non-subclassable 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 do not exist) or instances of superclasses ( upcasting a reference type violates the type system). Because the exact type of the object being referenced is known before execution, early binding (also called static dispatch ) can be used instead of late binding (also called dynamic dispatch ), 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.

Non-overridable methods

edit

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 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

edit

If a superclass method is a virtual method , then invocations of the superclass method will be dynamically dispatched . Some languages require that method 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 .

Visibility of inherited members

edit

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++. [ 14 ]

Base class visibility
Derived class visibility

Private derivation
Protected derivation
Public derivation

* Private →

* Protected →

* Public →

* Not inherited

* Private

* Private

* Not inherited

* Protected

* Protected

* Not inherited

* Protected

* Public

Applications

edit

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

Overriding

edit

Main article: Method overriding

Illustration of method overriding
Many object-oriented programming languages 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. [ 15 ] An alternative to overriding is hiding the inherited code.

Code reuse

edit

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 example, subclasses SquareSumComputer and CubeSumComputer override the transform() method of the base class SumComputer . 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 square and cube respectively. The subclasses therefore compute the sum of the squares/cubes between two integers.

Below is an example of Java.

inputs() {\n return IntStream.rangeClosed(a, b)\n .boxed\n .collect(Collectors.toList());\n }\n\n public int compute() {\n return inputs().stream().\n .mapToInt(this::transform)\n .sum();\n }\n}\n\nclass SquareSumComputer extends SumComputer {\n public SquareSumComputer(int a, int b) {\n super(a, b);\n }\n\n @Override\n public int transform(int x) {\n return x * x;\n }\n}\n\nclass CubeSumComputer extends SumComputer {\n public CubeSumComputer (int a, int b) {\n super(a, b);\n }\n\n @Override\n public int transform(int x) {\n return x * x * x;\n }\n}\n"}}"> import java.util.List ;
import java.util.stream.Collectors ;
import java.util.stream.IntStream ;

abstract class SumComputer {
private int a ;
private int b ;

public SumComputer ( int a , int b ) {
this . a = a ;
this . b = b ;
}

// Abstract method to be implemented by subclasses
public abstract int transform ( int x );

public List < Integer > inputs () {
return IntStream . rangeClosed ( a , b )
. boxed
. collect ( Collectors . toList ());
}

public int compute () {
return inputs (). stream ().
. mapToInt ( this :: transform )
. sum ();
}
}

class SquareSumComputer extends SumComputer {
public SquareSumComputer ( int a , int b ) {
super ( a , b );
}

@Override
public int transform ( int x ) {
return x * x ;
}
}

class CubeSumComputer extends SumComputer {
public CubeSumComputer ( int a , int b ) {
super ( a , b );
}

@Override
public int transform ( int x ) {
return x * x * x ;
}
}

In most quarters, class inheritance for the sole purpose of code reuse has fallen out of favor. [ citation needed ] 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. [ citation needed ] 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. [ 16 ]

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. [ 17 ]

Inheritance vs subtyping

edit

Further information: Subtyping

Inheritance is similar to but distinct from subtyping . [ 4 ] 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 methodOfA () const {
// ...
}
};

class B : public A {
public :
void methodO

Links found on this page

  1. Home [direct]
  2. Random [direct]
  3. Nearby [direct]
  4. Create account [direct]
  5. Log in [direct]
  6. Settings [direct]
  7. Donate Now If Wikipedia is useful to you, please give today. [direct]
  8. About Wikipedia [direct]
  9. Disclaimers [direct]
  10. Article [direct]
  11. Talk [direct]
  12. Edit [direct]
  13. classical tradition [direct]
  14. cleanup [direct]
  15. quality standards [direct]
  16. improve this article [direct]
  17. Learn how and when to remove this message [direct]
  18. object-oriented programming [direct]
  19. object [direct]
  20. class [direct]
  21. prototype-based inheritance [direct]
  22. class-based inheritance [direct]
  23. implementation [direct]
  24. base class [direct]
  25. C++ [direct]
  26. constructors [direct]
  27. overloaded operators [direct]
  28. friend functions [direct]
  29. realizing an interface [direct]
  30. interfaces [direct]
  31. directed acyclic graph [direct]
  32. delegation [direct]
  33. subtyping [direct]
  34. C# [direct]
  35. Scala [direct]
  36. is-a [direct]
  37. object composition [direct]
  38. composition over inheritance [direct]
  39. has-a [direct]
  40. strict partial order [direct]
  41. edit [direct]
  42. Tony Hoare [direct]
  43. Ole-Johan Dahl [direct]
  44. Kristen Nygaard [direct]
  45. Simula [direct]
  46. Smalltalk [direct]
  47. Java [direct]
  48. Python [direct]
  49. edit [direct]
  50. Objective C [direct]
  51. Brad Cox [direct]
  52. Bjarne Stroustrup [direct]
  53. edit [direct]
  54. modular [direct]
  55. language [direct]
  56. instance variables [direct]
  57. member functions [direct]
  58. Eiffel [direct]
  59. contracts [direct]
  60. reused [direct]
  61. compile-time [direct]
  62. method signature [direct]
  63. edit [direct]
  64. class modifiers [direct]
  65. Java [direct]
  66. C++11 [direct]
  67. binaries [direct]
  68. source code [direct]
  69. compile time [direct]
  70. upcasting [direct]
  71. early binding [direct]
  72. static dispatch [direct]
  73. late binding [direct]
  74. dynamic dispatch [direct]
  75. virtual method table [direct]
  76. multiple inheritance [direct]
  77. single inheritance [direct]
  78. edit [direct]
  79. private [direct]
  80. edit [direct]