Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Inheritance (object-oriented programming)

From Wikipedia, the free encyclopedia
Process of deriving classes from, and organizing them into, a hierarchy
"Classical inheritance" redirects here. For later inheritance of ancient culture, seeclassical tradition.
This article mayrequirecleanup to meet Wikipedia'squality standards. The specific problem is:Cluttered. Please helpimprove this article if you can.(April 2015) (Learn how and when to remove this message)

Inobject-oriented programming,inheritance is the mechanism of basing anobject orclass upon another object (prototype-based inheritance) or class (class-based inheritance), retaining similarimplementation. Also defined as deriving new classes (sub classes) from existing ones such as super class orbase class and then forming them into a hierarchy of classes. In most class-based object-oriented languages likeC++, 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 andfriend 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 andinterfaces. The relationships of objects or classes through inheritance give rise to adirected acyclic graph.

An inherited class is called asubclass of its parent class or super class. The terminheritance is loosely used for both class-based and prototype-based programming, but in narrow use the term is reserved for class-based programming (one classinherits from another), with the corresponding technique in prototype-based programming being instead calleddelegation (one objectdelegates 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 withsubtyping.[4][5] In some languages inheritance and subtyping agree,[a] whereas in others they differ; in general, subtyping establishes anis-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 asinterface inheritance (without acknowledging that the specialization of type variables also induces a subtyping relation), whereas inheritance as defined here is known asimplementation inheritance orcode inheritance.[6] Still, inheritance is a commonly used mechanism for establishing subtype relationships.[7]

Inheritance is contrasted withobject composition, where one objectcontains another object (or objects of one class contain objects of another class); seecomposition over inheritance. In contrast to subtyping’sis-a relationship, composition implements ahas-a relationship.

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

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 1967Ole-Johan Dahl andKristen 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 theSimula 67 programming language.[10] The idea then spread toSmalltalk,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 onObjective 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]

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 classA serves as abase class for thederived classB, which in turn serves as abase class for thederived classC. The classB is known asintermediate base class because it provides a link for the inheritance betweenA andC. The chainABC is known asinheritance path.
A derived class with multilevel inheritance is declared as follows:
// C++ language implementationclassA{...};// Base classclassB:publicA{...};// B derived from AclassC:publicB{...};// 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, orchild classes aremodular derivative classes that inherit one or morelanguage entities from one or more other classes (calledsuperclass,base classes, orparent classes). The semantics of class inheritance vary from language to language, but commonly the subclass automatically inherits theinstance variables andmember functions of its superclasses.

The general form of defining a derived class is:[13]

classSubClass:visibilitySuperClass{// subclass members};
  • The colon indicates that the subclass inherits from the superclass. The visibility is optional and, if present, may be eitherprivate orpublic. The default visibility isprivate. Visibility specifies whether the features of the base class areprivately derived orpublicly derived.

Some languages also support the inheritance of other constructs. For example, inEiffel,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 consideredreused 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 atcompile-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 samemethod signature.

Non-subclassable classes

[edit]

In some languages a class may be declared asnon-subclassable by adding certainclass modifiers to the class declaration. Examples include thefinal keyword inJava andC++11 onwards or thesealed keyword in C#. Such modifiers are added to the class declaration before theclass keyword and the class identifier declaration. Such non-subclassable classes restrictreusability, particularly when developers only have access to precompiledbinaries and notsource code.

A non-subclassable class has no subclasses, so it can be easily deduced atcompile 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 calledstatic dispatch) can be used instead oflate binding (also calleddynamic dispatch), which requires one or morevirtual method table lookups depending on whethermultiple inheritance or onlysingle 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). Aprivate 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). Afinal method in Java, asealed method in C# or afrozen feature in Eiffel cannot be overridden.

Virtual methods

[edit]

If a superclass method is avirtual method, then invocations of the superclass method will bedynamically 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 asinline 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 visibilityDerived class visibility
Private derivationProtected derivationPublic 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

Manyobject-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 calledoverriding. 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 ishiding the inherited code.

Code reuse

[edit]

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

In the following Python example, subclassesSquareSumComputer andCubeSumComputer override thetransform() method of the base classSumComputer. The base class comprises operations to compute the sum of thesquares 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 itssquare andcube respectively. The subclasses therefore compute the sum of the squares/cubes between two integers.

Below is an example of Python.

classSumComputer:def__init__(self,a,b):self.a=aself.b=bdeftransform(self,x):raiseNotImplementedErrordefinputs(self):returnrange(self.a,self.b)defcompute(self):returnsum(self.transform(value)forvalueinself.inputs())classSquareSumComputer(SumComputer):deftransform(self,x):returnx*xclassCubeSumComputer(SumComputer):deftransform(self,x):returnx*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 ofpolymorphic substitutability—an instance of the reusing class cannot necessarily be substituted for an instance of the inherited class. An alternative technique, explicitdelegation, requires more programming effort, but avoids the substitutability issue.[citation needed] In C++ private inheritance can be used as a form ofimplementation 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 fromsubtyping.[4] Subtyping enables a giventype to be substituted for another type or abstraction and is said to establish anis-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 classesB andA, whereB is both a subclass and a subtype ofA and can be used as anA wherever aB is specified (via a reference, a pointer or the object itself).

classA{public:voidDoSomethingALike()const{}};classB:publicA{public:voidDoSomethingBLike()const{}};voidUseAnA(constA&a){a.DoSomethingALike();}voidSomeFunc(){Bb;UseAnA(b);// b can be substituted for an A.}

In programming languages that do not support inheritance as asubtyping 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 betweentypes. Inheritance, even in programming languages that support inheritance as a subtyping mechanism, does not necessarily entailbehavioral 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 theLiskov substitution principle.[18] (Compareconnotation/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

[edit]

Using inheritance extensively in designing a program imposes certain constraints.

For example, consider a classPerson that contains a person's name, date of birth, address and phone number. We can define a subclass ofPerson calledStudent that contains the person's grade point average and classes taken, and another subclass ofPerson calledEmployee 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, aPerson object can be either aStudent or anEmployee, but not both. Using multiple inheritance partially solves this problem, as one can then define aStudentEmployee class that inherits from bothStudent andEmployee. 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 forrepeated inheritance.
Static
The inheritance hierarchy of an object is fixed atinstantiation when the object's type is selected and does not change with time. For example, the inheritance graph does not allow aStudent object to become anEmployee object while retaining the state of itsPerson superclass. (This kind of behavior, however, can be achieved with thedecorator pattern.) Some have criticized inheritance, contending that it locks developers into their original design standards.[19]
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 stillcast the object to its superclass type. For example, there is no way to give a function a pointer to aStudent's grade point average and transcript without also giving that function access to all of the personal data stored in the student'sPerson 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.

Thecomposite 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

[edit]

Implementation inheritance has been controversial among programmers and theoreticians of object-oriented programming since at least the 1990s. Among the critics are the authors ofDesign Patterns, who advocate instead for interface inheritance, and favorcomposition over inheritance. For example, the decorator pattern (as mentionedabove) has been proposed to overcome the static nature of inheritance between classes. As a more fundamental solution to the same problem,role-oriented programming introduces a distinct relationship,played-by, combining properties of inheritance and composition into a new concept.[citation needed]

According toAllen Holub, the main problem with implementation inheritance is that it introduces unnecessarycoupling in the form of the"fragile base class problem":[6] 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.[19] Another way of stating this is that "inheritance breaksencapsulation".[20] The problem surfaces clearly in open object-oriented systems such asframeworks, where client code is expected to inherit from system-supplied classes and then substituted for the system's classes in its algorithms.[6]

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

Complex inheritance, or inheritance used within an insufficiently mature design, may lead to theyo-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.[citation needed] 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 asEntity–component–system) allow program users to define variations of an entity at runtime.

See also

[edit]

Notes

[edit]
  1. ^This is generally true only in statically-typed class-based OO languages, such asC++,C#, Java, andScala.

References

[edit]
  1. ^Johnson, Ralph (August 26, 1991)."Designing Reusable Classes"(PDF).www.cse.msu.edu.
  2. ^Madsen, OL (1989). "Virtual classes: A powerful mechanism in object-oriented programming".Conference proceedings on Object-oriented programming systems, languages and applications - OOPSLA '89. pp. 397–406.doi:10.1145/74877.74919.ISBN 0897913337.S2CID 1104130.
  3. ^Davies, Turk (2021).Advanced Methods and Deep Learning in Computer Vision. Elsevier Science. pp. 179–342.
  4. ^abCook, William R.; Hill, Walter; Canning, Peter S. (1990).Inheritance is not subtyping. Proceedings of the 17th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL). pp. 125–135.CiteSeerX 10.1.1.102.8635.doi:10.1145/96709.96721.ISBN 0-89791-343-4.
  5. ^Cardelli, Luca (1993).Typeful Programming (Technical report).Digital Equipment Corporation. p. 32–33. SRC Research Report 45.
  6. ^abcMikhajlov, Leonid; Sekerinski, Emil (1998).A study of the fragile base class problem(PDF). Proceedings of the 12th European Conference on Object-Oriented Programming (ECOOP). Lecture Notes in Computer Science. Vol. 1445. Springer. pp. 355–382.doi:10.1007/BFb0054099.ISBN 978-3-540-64737-9. Archived fromthe original(PDF) on 2017-08-13. Retrieved2015-08-28.
  7. ^Tempero, Ewan; Yang, Hong Yul; Noble, James (2013).What programmers do with inheritance in Java(PDF). ECOOP 2013–Object-Oriented Programming. Lecture Notes in Computer Science. Vol. 7920. Springer. pp. 577–601.doi:10.1007/978-3-642-39038-8_24.ISBN 978-3-642-39038-8.
  8. ^Hoare, C. A. R. (1966).Record Handling(PDF) (Technical report). pp. 15–16.
  9. ^Dahl, Ole-Johan;Nygaard, Kristen (May 1967).Class and subclass declarations(PDF). IFIP Working Conference on Simulation Languages. Oslo: Norwegian Computing Center.
  10. ^Dahl, Ole-Johan (2004)."The Birth of Object Orientation: the Simula Languages"(PDF).From Object-Orientation to Formal Methods. Lecture Notes in Computer Science. Vol. 2635. pp. 15–25.doi:10.1007/978-3-540-39993-3_3.ISBN 978-3-540-21366-6.
  11. ^"C++ Inheritance".www.cs.nmsu.edu. Archived fromthe original on 2023-09-24. Retrieved2018-05-16.
  12. ^Stroustrup, Bjarne (1994).The Design and Evolution of C++. Pearson. p. 417.ISBN 9780135229477.
  13. ^Schildt, Herbert (2003).The complete reference C++. Tata McGraw Hill. p. 417.ISBN 978-0-07-053246-5.
  14. ^Balagurusamy, E. (2010).Object Oriented Programming With C++. Tata McGraw Hill. p. 213.ISBN 978-0-07-066907-9.
  15. ^override(C# Reference)
  16. ^"GotW #60: Exception-Safe Class Design, Part 2: Inheritance". Gotw.ca. Retrieved2012-08-15.
  17. ^Venugopal, K.R.; Buyya, Rajkumar (2013).Mastering C++. Tata McGraw Hill Education Private Limited. p. 609.ISBN 9781259029943.
  18. ^Mitchell, John (2002). "10 "Concepts in object-oriented languages"".Concepts in programming language. Cambridge University Press. p. 287.ISBN 978-0-521-78098-8.
  19. ^abcHolub, Allen (1 August 2003)."Why extends is evil". Archived fromthe original on 24 February 2019. Retrieved10 March 2015.
  20. ^Seiter, Linda M.; Palsberg, Jens; Lieberherr, Karl J. (1996)."Evolution of object behavior using context relations".ACM SIGSOFT Software Engineering Notes.21 (6): 46.CiteSeerX 10.1.1.36.5053.doi:10.1145/250707.239108.
  21. ^America, Pierre (1991).Designing an object-oriented programming language with behavioural subtyping. REX School/Workshop on the Foundations of Object-Oriented Languages. Lecture Notes in Computer Science. Vol. 489. pp. 60–90.doi:10.1007/BFb0019440.ISBN 978-3-540-53931-5.

Further reading

[edit]
Authority control databases: NationalEdit this at Wikidata
Retrieved from "https://en.wikipedia.org/w/index.php?title=Inheritance_(object-oriented_programming)&oldid=1290676012"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp