Watch our 3-minute video to find out how you can learn Java with a live instructor.
Additional Resources

Interfaces

In this lesson of the Java tutorial, you will learn...
  1. Understand the concept of interfaces
  2. Define and write code using your own interfaces
  3. Use interfaces in the Java API

Interfaces

Interfaces define a standardized set of commands that a class will obey

The commands are a set of methods that a class implements

The interface definition states the names of the methods and their return types and argument signatures

  • there is no executable body for any method - that is left to each class that implements the interface

Once a class implements an interface, the Java compiler knows that an instance of the class will contain the specified set of methods

  • therefore, it will allow you to call those methods for an object referenced by a variable whose type is the interface

Implementing an interface enables a class to be "plugged in" in any situation that requires a specific behavior (manifested through the set of methods)

An analogy: a serial interface on a computer defines a set of pin/wire assignments and the control signals that will be used

  • the actual devices that can be used may do entirely different tasks: mouse, modem, etc.
  • but they are all controlled through the same digital instruction mechanism; the individual wires are specified to carry specific signals

Using an interface rather than inheritance to specify a certain set of methods allows a class to inherit from some other class

  • in other words, if a class needs two different sets of methods, so it can behave like two different types of things, it could inherit one set from class A, and use an interface B to specify the other
  • you could then reference one of these objects with either an A reference or a B reference

Interfaces can also specify constants that are public, static, and final

Creating an Interface Definition

To create an interface definition:

  • define it like a Java class, in its own file that matches the interface name
  • use the keyword interface instead of class
  • declare methods using the same approach as abstract methods
    • note the semicolon after each method declaration - and that no executable code is supplied(and no curly braces)
    • the elements will automatically be public and abstract, and cannot have any other state; it is OK to specify those terms, but not necessary (usually public is specified and abstract is not - that makes it easy to copy the list of methods, paste them into a class, and modify them )
  • The access level for the entire interface is usually public
    • it may be omitted, in which case the interface is only available to other classes in the same package (i.e., in the same directory)
    • note, for the sake of completeness, there are situations where the interface definition could be protected or private; these involve what are called inner classes
Syntax
[modifiers] interface InterfaceName {
 
 // declaring methods
 
[public abstract] returnType methodName1(arguments);
 
 // defining constants
 
[public static final]
 type propertyName = value;
}

Example:

Code Sample: Java-Interfaces/Demos/Printable.java

public interface Printable {
 void printAll();
}
Code Explanation

This interface requires only one method. Any class implementing Printable must contain a public void printall() method in order to compile

Because the above interface is defined as public, its definition must be in its own file, even though that file will be tiny

An interface definition may also define properties that are automatically public static final - these are used as constants

Implementing Interfaces

A class definition may, in addition to whatever else it does, implement one or more interfaces

Once a class states that it implements an interface, it must supply all the methods defined for that interface, complete with executable code

  • note: it actually does not have to implement all of them, but in that case the class cannot be instantiated- it must be declared as an abstract class that can only be used as a base class (where some derived class would then fully implement the interface)

To implement an interface:

  • add that the class implements the interface to the class declaration
  • add the methods specified by the interface to the body of the class
    • note that you do need to specify the access terms on methods in a class that implements an interface
Syntax
[modifiers] class ClassName implements InterfaceName { 

 any desired properties
 
 // implement required methods
 [modifiers] returnType methodName1(arguments) {
  executable code
 }

 any other desired methods

}

It is important to note that a class may implement an interface in addition to whatever else it might do, so it could have additional properties and methods not associated with the interface

A class may implement more than one interface - that merely adds to the list of required methods

  • use a comma-separated list for the interface names
Syntax
[modifiers] class ClassName implements Interface1Name, Interface2Name {

 // must implement all methods from all implemented interfaces
 
}

Implementing Interfaces - Example

The complete example will use three separate files (the third file is shown in a few pages):

Code Sample: Java-Interfaces/Demos/Printable.java

public interface Printable {
 void printAll();
}

Code Sample: Java-Interfaces/Demos/PrintableThings.java

class Person implements Printable {
 private String name = new String("Bill");
 private int age = 22;
 public void printAll() {
  System.out.println("Name is " + name + ", age is " + age);
 }
}
class Stock implements Printable {
 private String tickerSymbol = new String("XYZ");
 private int shares = 100;
 private int currentPrice = 4000; // in pennies
 public void printAll() {
  System.out.println(tickerSymbol + " " + shares +
            " shares at " + currentPrice);
  System.out.println("Value: " + currentPrice * shares);
 }
 public void sell() {
  System.out.println(tickerSymbol + " sold");
 }
}
Code Explanation

This file contains two classes with package access. Both implement the Printable interface, but are otherwise not related. Stock has another method not related to Printable.

Reference Variables and Interfaces

An interface is like a class where ther internal structure and some of the behavior is hidden

  • interfaces are listed like classes in the API documentation
  • they compile to a .class file, and get loaded by the same process that loads true classes

Since a class that implements an interface is a class in all other respects, you can create a reference variable for that class, as usual

You can also create a reference variable whose type is the interface name

  • only the methods defined in the interface are visible through a variable whose type is the interface
    • if you do this, the only things you can access with that variable are the interface methods
    • for a Printable variable containing a Stock instance, the sell method is not visible, since it is not declared in Printable
  • any constants defined by the interface can be accessed without a prefix from code within the class, since implementing the interface makes them part of this class
  • for using a variable whose type is an interface, the same situations apply for as were discussed in the section on inheritance

To access an interface-implementing class with an interface class reference:

Syntax
[modifiers] InterfaceName variableName;

Example:

  • both Person and Stock implement Printable
  • therefore, we can create a reference variable to a Printable, and assign either a Person or a Stock object to it
  • we can then call the printAll() method from the Printable reference variable, since the compiler knows that method will exist, no matter which type of object is actually stored in the variable
Person p = new Person();
Stock s = new Stock();
Printable pr;
pr = p;

or

pr = s;

or

pr = new Person();

Calling an Interface Method

If you have a variable that is declared as a reference to the interface type, you can use it to call an interface method

  • note that you cannot call any of the additional methods that are not defined by the interface

Code Sample: Java-Interfaces/Demos/PrintableTest.java

public class PrintableTest {
 public static void main(String[] args) {
  Person p = new Person();
  Stock s = new Stock();

  p.printAll();
  s.printAll();

  Printable pr;
  pr = p;
  pr.printAll();
  pr = s;
  pr.printAll();
 }
}
Code Explanation

Once pr has been assigned a Printable instance, we can call pr.printAll();

  • we cannot directly call the sell() method when pr refers to a Stock, since the compiler would not associate it with a variable whose type was Printable

Note: to compile this, use *.java; since the name of the file containing Stock and Person is PrintableThings.java, the compiler won't be able to find those classes, since it would be looking for Person.java and Stock.java.

Note: you can test the type of object actually contained in an interface reference, and typecast it back to that type

  • for instance, to use the sell() method for a Stock:
if (pr instanceof Stock) ((Stock) pr).sell();

Interfaces and Inheritance

If a class implements an interface, then all subclasses of it will also automatically implement the interface

  • they are guaranteed to have the necessary methods available
  • it is a good practice to specify that the derived class implements the interface, just for self-documentation of the code (also for purposes of javadoc, if the base class is not in the same group of files)

An interface definition can inherit from another interface

  • the new interface then adds properties and methods to the existing (base) definition
  • a class that implements the new interface must implement all methods from the base interface as well as all the additional methods from the new interface definition

The following interface extends the Printable interface and adds another required method (the new method overloads printAll to print to a specified destination instead of to System.out):

Code Sample: Java-Interfaces/Demos/Printable2.java

import java.io.PrintStream;
public interface Printable2 extends Printable {
 public void printAll(PrintStream p);
}

A class implementing Printable2 must define both versions of printAll

Code Sample: Java-Interfaces/Demos/Printable2Test.java

import java.io.PrintStream;
class Cat implements Printable2 {
 public void printAll() {
  printAll(System.out);
 }
 public void printAll(PrintStream out) {
  out.println("Meow");
 }
}

public class Printable2Test {
 public static void main(String[] args) {
  Printable2 c = new Cat();
  c.printAll(System.err);
  c.printAll();
 }
}

Exercise: Exercise: Payroll-Interfaces01

Duration: 40 to 60 minutes.

It turns out that our hypothetical system is to be used for all payments our company makes, not just payroll checks- things like invoices will be paid through the system as well

  1. Create a finance package, and within it create an interface called Payable
    • It should define the public String getPayInfo() method that our employee classes already implement
  2. Specify that all the employee classes implement Payable
  3. The Solutions\Payroll-Interfaces01 directory contains a package called vendors with a class named Invoice - copy this directory to your working directory
  4. Modify the payroll program by adding an array of several invoices (you can just hard-code them)
  5. Create an array of type Payable whose size is the sum of the employee and invoice arrays sizes, then use System.arraycopy twice to combine the employee and invoice arrays into it (remember that for the second array, the starting point for the destination array will be the first array's length value)
  6. Loop through the combined array to get and print the payment info for each item

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() {
  guiComponent.addActionListener(this);
 }
}

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

  • this is particularly useful for gaining the add and remove listener logic, which is implemented in the base class

Interfaces and "Pluggable Components"

The TableModel interface

The Swing classes contain a component called JTable, which displays a spreadsheet-like grid

  • 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

  • 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: Java-Interfaces/Demos/TableModelExample.java

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) {
  super(title);
  JTable jt;
  this.setDefaultCloseOperation(EXIT_ON_CLOSE);
  jt = new JTable(model);
  setSize(600,170);
  getContentPane().add(jt);
 }
}

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();
  System.out.println("-------------- -------------- -------------- ");
  for (int r = 0; r < rows; r++) {
   for (int c = 0; c < cols; c++) {
    System.out.print(fixedStringLength(model.getValueAt(r, c).toString(), 15));
   }
   System.out.println();
  }
 }
 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) {
  java.io.PrintStream out = System.out;
  int rows = model.getRowCount();
  int cols = model.getColumnCount();
  out.println("<html><Head><title>My Table</title></head>");
  out.println("<body><table border='1' cellpadding='8' cellspacing='0'><tr>");
  for (int c = 0; c < cols; c++) {
   out.print("<th>" + model.getColumnName(c) + "</th>");
  }
  out.println("</tr>");
  for (int r = 0; r < rows; r++) {
   out.println("<tr>");
   for (int c = 0; c < cols; c++) {
    System.out.print("<td>" + model.getValueAt(r, c) + "</td>");
   }
   out.println("</tr>");
  }
  out.println("</table></body></html>");
 }
}
Code Explanation

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 ...

Interfaces Conclusion

In this lesson of the Java tutorial you have learned:

  • How to declare, implement, and use interfaces
To continue to learn Java go to the top of this page and click on the next lesson in this Java Tutorial's Table of Contents.
Last updated on 2009-03-02

Use of http://www.learn-java-tutorial.com (Website) implies agreement to the following:

Copyright Information

All pages and graphics on Website are the property of Webucator, Inc. unless otherwise specified.

None of the content on Website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of pages or content on Website

This content may not be printed or saved. It is for online use only.


Linking to Website

You may link to any of the pages on Website; however, you may not include the content in a frame or iframe without written permission from Webucator, Inc.


Warranties

Website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).


For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm