facebook twitter
Webucator's Free Java Tutorial

Lesson: Interfaces

Welcome to our free Java tutorial. This tutorial is based on Webucator's Introduction to Java Training course.

In this lesson, you will learn about interfaces and annotations.

Lesson Goals

  • Learn about the concept of interfaces.
  • Define and write code using your own interfaces.
  • Use interfaces in the Java API.


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. Often there is no executable body for methods; this is left to each class that implements the interface. (As of Java 8, an interface can fully define a method but we do not cover that in this course.)

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.

One useful way to think of an interface is as a contract: any class that implements the interface agrees to (must) implement all of the methods and fields defined in the interface.

Implementing an interface enables a class to be "plugged in" to 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. Note that:

  • The actual devices that can be used may do entirely different tasks: mouse, keyboard, monitor, 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).
    • As of Java 8 the interface can include static and default methods. This is beyond the scope of this course.
  • 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.


[modifiers] interface InterfaceName {

// declaring methods
[public abstract] returnType methodName1(arguments);

// defining constants
[public static final] type fieldName = value;


Code Sample:

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


Implementing an Interface

[modifiers] class ClassName implements InterfaceName {

any desired fields

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


Implementing Multiple Interfaces

[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 will be shown shortly):

Code Sample:

public interface Printable {
  void printAll();

Code Explanation

Code Sample:

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. Since the classes are not public, they can both be in the same file, and the file name does not need to match either class name. This is done purely as a convenience; it is not a good programming practice in general, but is sometimes useful if one class is highly coupled (interrelated) with the other, which is not the case here. Both classes 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 the 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.
    • 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.

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


Creating a Reference Variable for an Interface

[modifiers] InterfaceName variableName;


  • 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;


pr = s;


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:

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

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 fields 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.
  • An interface can actually extend multiple base interfaces, in which case the combination of all the methods will be required for any implementing class.

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:

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

Code Explanation

A class implementing Printable2 must define both versions of printAll.

Code Sample:

import java.io.PrintStream;
class Cat implements Printable2 {
  public void printAll() {
  public void printAll(PrintStream out) {

public class Printable2Test {
  public static void main(String[] args) {
    Printable2 c = new Cat();

Exercise: Payroll-Interfaces01

Duration: 30 to 40 minutes.

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

  1. Open the files in Java-Interfaces/Exercises/Payroll-Interfaces01/.
  2. Within the finance package directory, create an interface called Payable.
    • This interface should define the public String getPayInfo() method that our employee classes already implement.
  3. Specify that all the employee classes implement Payable.
  4. The Java-Interfaces/Exercises/Payroll-Interfaces01 directory contains a package called vendors with a class named Invoice. Modify the payroll program by adding an array inv of several invoices (you can just hard-code them).
  5. The finance directory contains a file named CheckPrinter.java. The class has a printChecks(Payable[]) method that you can call twice, once for employees and again for invoices.


package finance;

public interface Payable {	

	public String getPayInfo();


Code Explanation

This interface declares the public String getPayInfo() method that our employee classes already implement. No change is required to any other code, but we can now be sure that any object of a class that implements interface Payable will be able to call method getPayInfo().


package employees;
import finance.Payable;

public class Employee extends Person ]]>implements Payable {
	private static int nextId = 1;
	private int id = nextId++;
	private int dept;
	private double payRate;
	public Employee() {
	public Employee(String firstName, String lastName) {
		super(firstName, lastName);
	public Employee(String firstName,String lastName, int dept) {
		super(firstName, lastName);
	public Employee(String firstName, String lastName, double payRate) {
		super(firstName, lastName);
	public Employee(String firstName, String lastName, 
				int dept, double payRate) {
		this(firstName, lastName, dept);

	public static int getNextId() {
		return nextId;
	public static void setNextId(int nextId) {
		Employee.nextId = nextId;
	public int getId() {	return id;	}

	public int getDept() { return dept; }

	public void setDept(int dept) {
		this.dept = dept;

	public double getPayRate() { return payRate; }

	public void setPayRate(double payRate) {
		this.payRate = payRate;

	public String getPayInfo() {
		return "Employee " + id + " dept " + dept + " " +
					getFirstName() + " " + getLastName() + 
					" paid " + payRate;

Code Explanation

The class has been marked as implementing Payable. Although it would not be required, we should (and do) mark the derived classes the same way, to have more self-documenting code.

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) {
    java.io.PrintStream out = System.out;
    int rows = model.getRowCount();
    int cols = model.getColumnCount();
    out.println("My Table");
    for (int c = 0; c < cols; c++) {
    for (int r = 0; r < rows; r++) {
      for (int c = 0; c < cols; c++) {
" + model.getColumnName(c) + "
" + model.getValueAt(r, c) + "
"); } }

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


An annotation is a piece of descriptive data (metadata) about a class, field, or method. It is somewhat like a comment, except that individual annotations are predefined, reusable, and can have effects on either the compilation process or the use of the class once compiled. If you have used an IDE like Eclipse or NetBeans, you may have seen the @Override annotation on editor-supplied template code. This particular annotation tells the compiler that the method that immediately follows is meant to override a base class method (or a method required by an interface). If it does not (because perhaps you spelled the name incorrectly, or got the parameter list wrong), then a compiler error is issued.

Annotations provide Java with a means to achieve, at least to some extent, Aspect-Oriented Programming, or AOP. AOP recognizes cross-cutting concerns, that is, aspects of an element that cut across classes that might not be related by inheritance or implementation of an interface.

An example is a Java web service. While servlets usually extend a Java EE base class (and will always implement the Servlet interface), there is no specified base class or interface for a web service. Instead, configuration information informs the web server that a specific class is intended to be used as a web service, and the server takes steps to make that happen.

Annotation Details

  • Annotations are defined as a sort of interface, but an @ symbol precedes the interface keyword in the declaration (as in @interface). When used, an @ symbol is prepended to the name.
  • They can be parameterized with optional elements.
    • A parameter element named value is special - if it is the only element, then it does not need to be named when used (a single value passed to the annotation will be assumed to be the value).
    • For annotations accepting only one parameter, that parameter should be named value.
    • An annotation with no parameters serves as a marker, much like implementing the Serializable interface.
  • They are used as modifiers preceding any target code entities that are declared: class, field, method, constructor, method parameters, return values, package, or local variables.
  • Based on their specified retention policy, they can be discarded after compilation (the SOURCE policy), or preserved into the compiled class (CLASS persists, but the JVM isn't required to keep the information after the class is loaded, and RUNTIME annotations do remain with the class in the JVM).
    • @Override is an example of the source type, since it is only needed by the compiler
    • A runtime type that you might encounter the effect of is @Deprecated, which states that an element is deprecated - you will receive a compiler warning if your code uses an element marked with this annotation (and, since you might be accessing the element in an already-compiled class, this annotation must persist into the compiled class file).
    • @SuppressWarnings is another source annotation, with an optional element to specify what types of warnings are to be suppressed.
  • The annotation definitions are themselves annotated: -@Target and @Retention are used before the annotation definition to specify which type of element receives the annotation, and what the retention is.

Using Annotations

To apply an annotation to a class or element, precede the item with the name of the annotation, prefixed with the @ symbol.

If the annotation takes parameters, supply them in parentheses, as a comma separated list of parameterName=parameterValue. If the only parameter is called value, then you can just supply the parameterValue, without specifying it by name.


Using an Annotation

Name(value=parameterValue, parameter2Name=parameter2Value, ...)

Code Sample:

public class AnotherClass {
	public void myMethod() {
		System.out.println("This method is overridden in MyClass");

class MyClass extends AnotherClass {
	public void myMethod() {
		System.out.println("myMethod overrides the method in AnotherClass");
	public void myMethod(int i) {
		System.out.println("myMethod is an overload");

Code Explanation

The @Override annotation indicates that myMethod() in MyClass overrides in myMethod() in AnotherClass.