|
Expand
|
Minimize
|
InheritanceAnother big word for a simple concept. To help explain inheritance, we'll go back to our beer example. Say we want to define a new class to represent a pint of an imported French beer. This class would have all the variables and methods of the normal beer class, but it would have the following additional information:
(We need this information because we are students; everyone knows the price of Harp, but we would like to know the price of this expensive beer before we order it!) It would be rather tedious to define a new class,
A subclass is a class definition which derives functionality from another class definition. What this means is that we only need to define the
additional information that the
So, we create a new class,
We do not need to include any information about
Counters, Counters, Counters...Back to the counter example then! The counter we had in
the last section is fine for most counting purposes. But say
in a program we require a counter that can not only be
incremented, but can be decremented too. Since this new
counter is so similar in behaviour to our previous counter,
once again would be mad to define a brand new class with everything
that
class ReverseCounter extends Counter
{
public void DecrementCounter(void) {
MyCounter--;
}
}
The
We have defined
Inheritance is a powerful tool. Unlike our simple example,
inheritance can be passed on from generation to generation;
we could define a class
Bugs, bugs, bugs...If you tried to compile the above example and found it wasn't compiling, don't worry! There is a semi-deliberate mistake left in the code, which I am very usefully going to use to stress a point. When defining a class you must consider subclasses. When we defined the
class Counter extends Object {
private int MyCounter;
...
...
}
We can see that the variable
We should have realised at the time of writing the
protected int MyCounter;
A variable with a
Next: Conclusion. |
|
|
©2005 Contact
|