In this demo we begin with StartApplet4.java,
which includes the classes Test1
and Test2,
each of which implements an interface called Testable.
The classes implement aMethod()
from Testable.
We created a Testable
array that references instances of
Test1 and Test2.
We loop through this array and invoke aMethod()to
illustrate the power of an interface to add a common method to different
classes.
|
InterfaceApplet.java
(Output goes to browser's Java
console.)
|
public
class InterfaceApplet extends java.applet.Applet
{
public void init () {
Testable [] array = new Testable[2];
array[0] = new Test1 ();
array[1] = new Test2 ();
for (int i=0; i < 2; i++) {
System.out.println
("Call aMethod() in Test" + array[i].aMethod ());
}
}
// Paint message in Applet window.
public void paint (java.awt.Graphics g) {
g.drawString ("InterfaceApplet",
20, 20);
}
}
/** Test1 implements Testable. **/
class Test1 implements Testable
{
public int aMethod () {
return 1;
}
}
/** Test2 also implements Testable. **/
class Test2 implements Testable
{
public int aMethod () {
return 2;
}
}
/** Testable interface holds one method. **/
interface Testable
{
public int aMethod ();
}
|
InterfaceApp.java
|
|