Hierarchy and Class Design Terms
Inheritance
- Inheritance allows you to create a class from an existing class.
- This is one of the most important concepts in Object-Oriented Programming and allows you
to re-use code rather than maintain multiple copies of the same code.
- The existing class is called the parent,
super, or base class.
- The new class is called the child,
sub, or derived class.
- The child class just gets (inherits) anything defined in the parent class, including anything
that the super class has inherited.
- You do NOT recode anything that is already in the parent.
- Both attributes (instance variables)
and behaviors (instance methods) are inherited.
- The child class can add its own instance variables and methods, as needed.
- The idea is that each child class is a specialized version of its parent.
- In Java, use the keyword extends to create a child class.
- If the parent is not expicitly specified, it is the Object class; Object is the parent
of all classes in Java.
- Inheritance is a very powerful mechanism for reusing code and is an important feature of all object-oriented programming languages.
Hierarchies
- A class hierarchy
refers to a set of classes that are related by inheritence.
- A relationship that can be describe as X
hasa
Y commonly indicates that X is a class and Y is a data member or member
function of the class. (You already know this.)
- A relationship that can be describe as A
isa
B commonly indicates that A and B are both classes, and B is a super
class of A.
- If a class farther down in the hierarchy needs different behavior from its parent,
you can override the method.
- This means to write a method in the child with the exact signature of the method in the parent class.
- The child-class method can either completely replace or augment the corresponding
method in the superclass.
- Any member functions that are not overidden in the derived class will be
inherited from the super class.
- Note that this is different than overloading a method.
- Overloading means to have a method in the same class with the same name and a
different signature (either the number or class of arguments is different).