Home : Course Map : Chapter 4 : Java :
Demos 4: Interfaces
JavaTech
Course Map
Chapter 4

Introduction
Inheritance
  Demo 1
Overriding
  Demo 2a
  Demo 2b
this,super
MoreConstructors
  Demo 3
Abstraction
Interface 
  Demo 4
Casting References
MoreAboutArrays
Object class
Class Summary
Exercises

    Supplements
Override/Overload
Annotation-J2SE5.0
Java Security
Class Loading
Class Verifier
SecurityManager
     About JavaTech
     Codes List
     Exercises
     Feedback
     References
     Resources
     Tips
     Topic Index
     Course Guide
     What's New

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

 

 

 

            Tech
MoreComplexClass
ImprovedHistogram
JavaRandomNums
Vectors & Matrices
Exercises

           Physics
Runge-Kutta 2nd
  Demo 1
Runge-Kutta 4th
  Demo 2
BoundaryVal.Prob
Shooting Method
  Demo 3
Exercises

  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
21
22 23 24
Supplements

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.