Some Uses for Interfaces

Contact Us or call 1-877-932-8228
Some Uses for Interfaces

Some Uses for Interfaces

Interfaces and Event-Handling

A real-world use of interfaces is for event-handling

  • An object that can generate an event maintains a list of objects that would like to listen for that event (they will be notified when the event occurs by having one of their methods called).
  • The object that generates the event fires it by going through its list of objects that want to handle the event, and calling a specified interface method for each object.
  • A class may handle an event if it implements the interface that is expected for that event - therefore it will have the specified method.
  • You register an object to handle an event by passing a reference to it to the event-generating object's method that adds a handler.

Assuming that there is an event type called XXXEvent:

  • The handler interface would probably be named XXXListener.
  • The method to register a listener would usually be called addXXXListener.
  • The method generating the event probably has a protected utility method called fireXXXEvent that it uses to trigger the event notifications (and it is available for you to call if you extend the class).

The ActionListener interface is used for GUI events like button clicks.

  • The event is fired by the GUI object calling the actionPerformed method for any registered listeners (the code to do this is already built into the GUI classes, and the Java API defines the interface shown below).
public interface ActionListener {
	public void actionPerformed(ActionEvent e);

A class can listen for events if it implements ActionListener.

  • It can either register itself with the event-generating object, or code outside the class can register it - the example below shows how it would register itself using this:
public class MyClass implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		System.out.println("Event occurred");
	someOtherMethod() {

For the class that fires the event, registering is done with the addActionListener(ActionListener) method, which receives a reference to an ActionListener object:

  • It adds that reference to a list (maybe a java.util.Vector) of listeners.
  • When the time comes to fire the event, it walks through the list, calling actionPerformed() for each element on the list (and passing a reference to an event object that it creates).

For the sake of completeness, when the listener interface has multiple methods, there are often abstract classes that implement most or all of the methods as do-nothing methods - so that all you need to do is extend the class and implement the methods that you choose

Interfaces and "Pluggable Components"

The TableModel interface

The Swing classes contain a component called JTable, which displays a spreadsheet-like grid. Note that:

  • It uses a Model-View-Controller approach to separate these sections of logic into individual classes.
  • The TableModel interface defines a set of methods that allow a JTable (the controller) to query a data model to find out information in order to display it.
  • The interface forms a framework for a discussion that will take place between the controller and the model (like, "How many rows do you have?" and, "How many columns?", followed by "What's the value at column 0, row 0?", etc.).

Below are some of the methods from TableModel:

public interface TableModel
int getColumnCount()
Returns the number of columns in the model.
int getRowCount()
Returns the number of rows in the model.
String getColumnName(int columnIndex)
Returns the name of the column at columnIndex.
Class<?> getColumnClass(int columnIndex)
Returns the most specific superclass for all the cell values in the column.
Object getValueAt(int rowIndex, int columnIndex)
Returns the value for the cell at columnIndex and rowIndex.
boolean isCellEditable(int rowIndex, int columnIndex)
Returns true if the cell at rowIndex and columnIndex is editable.
void setValueAt(Object aValue, int rowIndex, int columnIndex)
Sets the value in the cell at columnIndex and rowIndex to aValue.

You can see the conversation that will take place between the controller and the model. Note that:

  • The controller will ask the model for the number of rows and columns, and, with that information, ask for the value at each location.
  • It will ask for the type of data with getColumnClass, so it can determine from its settings how to display the values (instances of Number, which Integer, Double, etc., extend, get right-aligned, Boolean columns use a check box, all others get left-aligned - these settings are configurable).
  • It will get a heading for each column with getColumnName.
  • If a cell is double-clicked, it can ask if the cell is editable with isCellEditable.
    • If it is, when the user is done editing, it can put the new data into the model using setValueAt.

Code Sample:

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;

public class TableModelExample {

  public static void main(String[] args) {

    DemoTableModel model = new DemoTableModel();

    new TableGUI("Table Model Example", model).setVisible(true);
    new TableConsole(model);
    new TableHTML(model);

class DemoTableModel extends AbstractTableModel {

    String[] titles = { "Name", "Active", "Grade" };
    String[] names = { "Mary", "Joe", "Sue" };
    Boolean[] actives = { new Boolean(true), new Boolean(false),
                          new Boolean(true) };
    Integer[] grades = { new Integer(99), new Integer(87),
                         new Integer(89) };
    public int getRowCount() { return names.length; }

    public int getColumnCount() { return 3; }

    public String getColumnName(int col) {
      return titles[col];

    public Object getValueAt(int row, int column) {
      if (column == 0) return names[row];
      else if (column == 1) return actives[row];
      else return grades[row];

    public void setValueAt(Object v, int row, int column) {}

    public Class getColumnClass(int column) {
      if (column == 0) return String.class;
      else if (column == 1) return Boolean.class;
      else return Integer.class;

    public boolean isCellEditable(int row, int column) {
      return false;

class TableGUI extends JFrame {

  public TableGUI(String title, DemoTableModel model) {
    JTable jt;
    jt = new JTable(model);

class TableConsole {

  TableModel model;

  public TableConsole(TableModel model) {

    int rows = model.getRowCount();
    int cols = model.getColumnCount();

    for (int c = 0; c < cols; c++) {
      System.out.print(fixedStringLength(model.getColumnName(c), 15));
    System.out.println("-------------- -------------- -------------- ");
    for (int r = 0; r < rows; r++) {
      for (int c = 0; c < cols; c++) {
          fixedStringLength(model.getValueAt(r, c).toString(), 15));
  private String fixedStringLength(String in, int size) {
    if (in.length() > size) in = in.substring(0, 15);
    char[] blankArray = new char[size - in.length()];
    for (int i = 0; i < blankArray.length; i++) blankArray[i] = ' ';
    return in + String.valueOf(blankArray);

class TableHTML {

  TableModel model;

  public TableHTML(TableModel model) { out = System.out;
    int rows = model.getRowCount();
    int cols = model.getColumnCount();
    out.println("<html><Head><title>My Table</title></head>");
      "<body><table border='1' cellpadding='8' cellspacing='0'><tr>");
    for (int c = 0; c < cols; c++) {
      out.print("<th>" + model.getColumnName(c) + "</th>");
    for (int r = 0; r < rows; r++) {
      for (int c = 0; c < cols; c++) {
        System.out.print("<td>" + model.getValueAt(r, c) + "</td>");

For convenience, all the classes are in one file.

The DemoTableModel class implements TableModel by extending AbstractTableModel, thus gaining implementations of several methods (like those relating to model change event listener lists), then adding the remaining methods.

The model is based on parallel arrays of student data: name, grade, and active or not- each array represents one column of data, and element 0 in each array is the same student.

The titles array holds column names.

getColumnCount returns 3, because we know that in advance.

getRowCount returns the length of one of the data arrays.

For getColumnName, we return an appropriate string from the titles array.

For getValueAt, we pick an array based on the column number, and return the element at the row index.

getColumnClass returns a class object that matches the type of data for each array.

isCellEditable returns false, and setValueAt does nothing, because our model is not editable.

We then have three possible views of the data: a Swing GUI view that uses a JTable, a console view that prints column-aligned data, and an HTML view that produces HTML code to the console (you can copy that and paste it into a file to view in a browser, like in tablemodel.html).

Since the JTable is the whole reason TableModel exists, it knows what to do with the model. The TableConsole and TableHTML view objects have to explicitly call the appropriate methods in order to display the data.

Marker Interfaces

It is actually possible to have an interface that requires no methods at all! This creates what is called a marker interface.

A declaration that a class implements the interface makes it an instance of that interface, so that it can be passed as a parameter to a method expecting an instance of the interface, or as a return value from a method that declares it returns an instance of the interface.

An example from the API is Serializable

  • An object that implements Serializable may be turned into a serial data stream, perhaps to save in a file or send across a network connection.
  • The writeObject method of ObjectOutputStream accepts a parameter whose type is Object, but throws an exception if it doesn't implement Serializable.
  • The serialization mechanism is recursive, so not only must the object be an instance of Serializable, but any of its object fields must also reference objects that are Serializable (or marked as transient), and any of their fields ... .