A key feature of object oriented programming concerns the ability
of a class to inherit an existing
class and increase its capabilities.
Here, for example, class B
inherits, or extends, class A
:
|
public
class
A
{
int i=0;
void doSomething
() {
i = 5;
}
}
class B extends
A
{
int j = 0;
void doSomethingMore
() {
j = 10;
i += j;
}
}
|
In the diagram at the left, by convention, the superclass
is on top and subclasses are below and point upwards to
the base class.
The class B above
then has capabilities equivalent to class B1
shown below:
class
B1
{
int i = 0;
int j = 0;
void doSomething
() {
i = 5;
}
void doSomethingMore
() {
j = 10;
i += j;
}
}
|
An instance of either class B
or B1
both possess i
and j
variables and the two methods. The class definition of class B
is much smaller than B1
because the compiler will link the members of the A
base class to class B.
Inheritance allows subclasses to build on a superclass
to add new capabilities while the superclass is still available
for situations where the new capabilities are not needed or applicable.
Inheritance does more than reduce the size of the
subclass definitions. We will see that the inheritance mechanism
offers several new capabilities including the ability to re-define,
or override, a method in the superclass
with a new one.
We can now create instances of class B and access methods
and data in both class B and class A (since they
are public - access modifiers will be discussed later.)
...
B b = new B (); //Create
an instance of class B
b.doSomething (); //Access
class A methods
b.doSomethingMore ();//And class
B methods
...
|
Another class can in turn inherit class B:
|
class
C extends B
{
int k;
void doEvenMore () {
doSomething ();
doSomethingMore ();
k = i + j;
}
}
|
Now an instance of class C
can use the class C data and methods and also those of both classes
B and C.
Note: Unlike C++, multiple
inheritance is not allowed in Java:
Interfaces, discussed later,
provide most of the benefits of multiple inheritance without the
drawbacks.
Latest update: Oct.24, 2004
|