Inheritance (object-oriented programming)
In object-oriented programming theory, inheritance is the practice of defining
object types which are specializations or extensions of existing object type, inheriting
common behaviors from the parent type while changing only what needs to change.
This encrouages code reuse, minimizes duplication of effort, and promotes consistency
of behavior between similar modules.
Most object-oriented languages accomplish this by allowing the programmer to specify,
in the coding of a class
For example, a Java program might have a class Animal
that contained such data elements as whether the animal was presently alive, where it is
currently located, etc.; as well as methods instructing the animal to eat, move, mate, etc.
If we wanted to create a class Mammal, most of those data elements and functions
would be the same as for most animals, but a few would change.
We therefore define Mammal as a subclass of Animal (we then
say that Animal is Mammal's superclass or parent class):
class Mammal extends Animal {
Hair m_h;
Breasts m_b;
Mammal reproduce() {
Mammal offspring;
super.reproduce();
if (self.is_female()) {
offspring = super.give_birth();
offspring.breastfeed(m_b);
}
care_for_young(offspring);
return offspring;
}
}
Note here that we don't need to specify that a mammal has all the usual animal things:
a location, ability to eat, move, etc.
We do add some addition features such as hair and breasts that are unique to mammals,
and we redefine the reproduce method to add functionality.
Within the reproduce method, note the call super.reproduce().
This is a call to the superclass method which we are redefining.
This roughly means "do whatever a member of my superclass would do", which is then
followed by code specific to our new subclass.
Some languages allow multiple inheritance, in which an object can inherit
behaviors and features from more than one superclass (this causes some confusing
situations, so there is some debate over whether or not its benefits outweigh its
risks).
Java compromises: it allows a class to inherit interfaces from more than one
parent (that is, one can specify that a class must have all of the same externally
exposed methods of its interface-parents, and allow the compiler to enforce that),
but can inherit actual methods and data from only one parent.