Java Reference
In-Depth Information
public class
A
{
int i
=
0;
void doSomething ()
{
i
=
5;
}
}
class
B
extends A {
int j = 0;
void doSomethingMore () {
j = 10;
i+= j;
}
}
The diagram on the left indicates the class hierarchy. By convention the
superclass
is on top, subclasses are below, and the arrow points upwards from the subclass
to the superclass The subclass
B
has all the data and methods from class
A
plus
the new data and methods added by
B
.Wecan think of class
B
as having the data
and methods equivalent to an imaginary class (let's call it
“BA
„
) shown here:
class
BA
{
int i
=
0;
int j
=
0;
void doSomething ()
{
i
=
5;
}
void doSomethingMore ()
{
j = 10;
i+= j;
}
}
By using inheritance we get the features of the imaginary class
BA
without having
to duplicate the code from the base class
A
.Wecan now create instances of class
B
and access methods and data in both class
B
and class
A
:
...
Bb= new B (); // Create an instance of class B
b.doSomething (); // Access a method defined in class A
b.doSomethingMore (); // And a method defined in class B
...
Another class can, in turn, inherit from class
B
,asshown here with class
C
:
Search WWH ::
Custom Search