Multiple inheritance and overriding . An interface or class inherits the methods that are defined
in an interface that it implements, but it always overrides them. Because a class
may implement several interfaces, a method with the same signature may be
inherited from several interfaces. This is not a problem because only the signa-
ture is given in the interface, not the method body. For a complete explanation
of and rules governing multiple inheritance, see the footnotes at the bottom of
lesson page 12-2 of ProgramLive .
and a call of the method that has ob as its argument:
Java automatically casts ob to type I when assigning ob to parameter par .
The contents of a variable of an interface type
Below, we define and initialize two variables of type I :
I x1= (I) ob;
I x2= ob;
Variables x1 and x2 contain the name of the complete object ob , but the only
components that can be referenced are those available from apparent type I .
Thus, component x1.p can be referenced. But what does x1.p refer to? Using
the same kind of rules as for subclasses, the real type of x1 is used to determine
this: it refers to the method of the same name that is defined in class G . Just as
with classes and subclasses, we can say that method p that is defined in class G
overrides the unimplemented method in interface I .
Of course. You can cast x1 from the interface-type back to G :
G h= (G) x1;
thus obtaining again the ability to access all components of the object.
Implementing several interfaces
In return for having a class C implement an interface, a service is provided. For
example, if C implements ActionListener , the implemented method action-
Performed in C will be called when a corresponding button is clicked.
As another example, in the next section, we discuss interface Comparable .
To implement Comparable , a class C has to define method compareTo , which
provides an ordering on the objects of class. In return, several methods can be
used to search and sort arrays whose base type is class C .
/** = -1 if this object < b,
* 0 if this object =b , and
* 1 if this object >b */
int compareTo(Comparable b);