- Inheritance (object-oriented programming)
-
In object-oriented programming (OOP), inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support. In classical inheritance where objects are defined by classes, classes can inherit attributes and behavior (i.e., previously coded algorithms associated with a class) from pre-existing classes called base classes or superclasses or parent classes or ancestor classes. The new classes are known as derived classes or subclasses or child classes. The relationships of classes through inheritance gives rise to a hierarchy. In prototype-based programming, objects can be defined directly from other objects without the need to define any classes, in which case this feature is called differential inheritance.
Complex inheritance, or inheritance used within an insufficiently mature design, may lead to the yo-yo problem.
The inheritance concept was invented in 1968 for Simula.[1]
Contents
Subclasses and superclasses
A superclass, base class, or parent class is a class from which other classes have been derived. The classes that are derived from a superclass are known as subclasses, or derived classes, or child classes.
A superclass allows for a generic interface to include specialized functionality through the use of virtual functions.
The superclass mechanism is extensively used in object-oriented programming because of the reusability that can be achieved: common features are encapsulated in modular objects. Subclasses that wish to implement special behavior can do so via virtual methods, without having to reimplement the superclass's behavior.
A subclass is a class that inherits some properties from its superclass.
Subclasses and superclasses are often referred to as derived and base classes, respectively,
Applications
Inheritance is used to co-relate two or more classes to each other. With the use of inheritance we can use the methods and the instance variables of other classes in any other classes.
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 usually 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 behave according to the base class. For instance, in C#, the overriding of a method should be specified by the program. An alternative to overriding is hiding the inherited code.
Code reuse
One of the earliest motivations for using inheritance was the reuse of code that already existed in another class. This practice is usually called implementation inheritance. Before the object-oriented paradigm was in use, one had to write similar functionality over and over again. With inheritance, behaviour of a superclass can be inherited by subclasses. It not only possible to call the overridden behaviour (method) of the ancestor (superclass) before adding other functionalities, one can override the behaviour of the ancestor completely.
For instance, when programming animal behaviour, there may be the class of bird, of which all birds are derived. All birds may use the functionality of flying, but some may fly with a different techniques (swinging, using thermic winds like Albatroses). So, flying bird may use all the behaviour of birds, or call it and add some other behaviour for the bird species. And some that cannot fly anymore, like kiwi, would override it with a method having no behaviour at all.
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, 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.[2]
Object Oriented-Software Construction, 2nd edition by Bertrand Meyer, the creator of the object-oriented programming language Eiffel, lists twelve different uses of inheritance,[3] most of which involve some amount of implementation inheritance.[dubious ]
Forms of inheritance
- Single inheritance
- When a subclass inherits only from one base class
- Multiple inheritance
- When a subclass inherits from multiple base classes.
- Hierarchical inheritance
- When many subclasses inherit from a single base class
- Multilevel inheritance
- When a subclass inherits from a class that itself inherits from another class. The transitive nature of inheritance is reflected by this form of inheritance.
- Hybrid inheritance
- A combination of two or more forms of inheritance; for example, when a subclass inherits from multiple base classes and all of its base classes inherit from a single base class
Inheritance vs subtyping
Subtyping enables a given type to be substituted for another type or abstraction. Subtyping is said to establish an is-a relationship between 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 a both a subclass and a subtype of A and can be used as an A wherever a reference (i.e., a reference or a pointer) to an A is specified.
class A { public: DoSomethingALike(){} }; class B : public A { public: DoSomethingBLike(){} }; 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 (i.e., 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.[4] (Compare connotation/denotation.) In some, but not all 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.
Limitations and alternatives
When using inheritance extensively in designing a program, one should note certain constraints that it imposes.
For example, consider a class
Person
that contains a person's name, address, phone number, age, gender, and race. 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:
Design constraints
- Singleness: using single inheritance, a subclass can inherit from only one superclass. Continuing the example given above,
Person
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, it can still inherit from each superclass only once; this scheme does not support cases in which a student has two jobs or attends two institutions.
- 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
Student
object to become aEmployee
object while retaining the state of itsPerson
superclass. (Although similar behavior can be achieved with the decorator pattern.) Some have criticized inheritance, contending that it locks developers into their original design standards.[5]
- 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 the object to its superclass type. For example, there is no way to give a function a pointer to a
Student
'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. This largely mitigates this issue.
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.
Roles and inheritance
Sometimes inheritance-based design is used instead of roles. A role, say Student role of a Person describes a characteristic associated to the object that is present because the object happens to participate in some relationship with another object (say the person in student role -has enrolled- to the classes). Some object-oriented design methods do not distinguish this use of roles from more stable aspects of objects. Thus there is a tendency to use inheritance to model roles, say you would have a Student role of a Person modelled as a subclass of a Person. However, neither the inheritance hierarchy nor the types of the objects can change with time. Therefore, modelling roles as subclasses can cause the roles to be fixed on creation, say a Person cannot then easily change his role from Student to Employee when the circumstances change. From modelling point of view, such restrictions are often not desirable, because this causes artificial restrictions on future extensibility of the object system, which will make future changes harder to implement, because existing design needs to be updated. Inheritance is often better used with a generalization mindset, such that common aspects of instantiable classes are factored to superclasses; say having a common superclass 'LegalEntity' for both Person and Company classes for all the common aspects of both. The distinction between role based design and inheritance based design can be made based on the stability of the aspect. Role based design should be used when it's conceivable that the same object participates in different roles at different times, and inheritance based design should be used when the common aspects of multiple classes (not objects!) are factored as superclasses, and do not change with time.
One consequence of separation of roles and superclasses is that this cleanly separates compile-time and run-time aspects of the object system. Inheritance is then clearly a compile-time construct. it does influence the structure of many objects at run-time, but the different kinds of structure that can be used are already fixed at compile-time.
To model the example of
Person
as an employee with this method, the modelling ensures that aPerson
class can only contain operations or data that are common to every Person instance regardless of where they are used. This would prevent use of a Job member in a Person class, because every person does not have a job, or at least it is not known that the Person class is only used to model Person instances that have a job. Instead, object-oriented design would consider some subset of all person objects to be in an "employee" role. The job information would be associated only to objects that have the employee role. Object-oriented design would also model the "job" as a role, since a job can be restricted in time, and therefore is not a stable basis for modelling a class. The corresponding stable concept is either "WorkPlace" or just "Work" depending on which concept is meant. Thus, from object-oriented design point of view, there would be a "Person" class and a "WorkPlace" class, which are related by a many-to-many associatation "works-in", such that an instance of a Person is in employee role, when he works-in a job, where a job is a role of his work place in the situation when the employee works in it.Note that in this approach, all classes that are produced by this design process form part of the same domain, that is, they describe things clearly using just one terminology. This is often not true for other approaches.
The difference between roles and classes is especially difficult to understand, if one assumes referential transparency, because roles are types of references and classes are types of the referred-to objects.
See also
- Circle-ellipse problem
- Class (object-oriented programming)
- Composition in object-oriented programming
- Defeasible reasoning
- Differential inheritance
- Interface (computer science)
- Interface inheritance
- Multiple inheritance
- Override (object-oriented programming)
- Polymorphism in object-oriented programming
- Role-Oriented Programming
- The Third Manifesto
- Virtual inheritance
References
- ^ How Object-Oriented Programming Started – By Dahl and Nygaard
- ^ http://www.gotw.ca/gotw/060.htm
- ^ Meyer, Bertrand (1997). Object-Oriented Software Construction, second edition. Prentice Hall. ISBN 0-13-629155-4. Chapter 24.
- ^ 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.
- ^ Why extends is evil - JavaWorld
Categories:
Wikimedia Foundation. 2010.