Overview


Here we show several example coded interfaces. Note how simple the code is (method headers only).

Association
An "Association" is explained here...
/* Interface: Association
 */

public interface Association<ValueType> {
	public String getKey();
	public ValueType getValue();
}

Drawable
A "Drawable" represents a type that can be drawn.

Possible implementors of this interface could include:

  • Road
  • Planet
  • Tree
  • Car
  • Person
  • etc and etc...
import java.awt.Graphics;

public interface Drawable {

	//Draw this object on graphics (canvas)
	public void drawOn(Graphics g);

	//Move this object by x and y
	public void moveBy(int x, int y);

	//Grow this object factor
	//e.g. factor=2 would double size
	public void growBy(double factor);

}
Report
I am an interface (contract) for a "Report".

Possible implementors of this interface could include:

  • HtmlReport
  • TextReport
  • RichTextReport
  • PDFReport
  • etc...
import java.util.List;

public interface Report {

	public void showText(String text);
	public void showTitle(String title);
	public void showHeading(String heading, boolean isBold);
	public void showTable(List<List<String>> tableData);

}
Weighable
Full step-by-step example is here...
/* A warm hello
 * I'm a Weighable type (interface)
 * I know how to do one thing: Answer a weight. */

public interface Weighable {
	public int getWeight();
}

Printable
Full step-by-step example is here...
import java.io.PrintStream;

/* Interface Printable
 * I know how to print myself on a report */

public interface Printable {
	public void printOn(PrintStream report);
}


Interface Compared to Class (Including Generics)


Left: Interface With Generics
Right: Class With Generics
public interface Association<ValueType> {
	public String getKey();
	public ValueType getValue();
}

public class Association2< ValueType> implements Association<ValueType> {
	private String key;
	private ValueType value;