Defining Interfaces

Python Java
No interfaces, only classes! The form of an interface is public interface <name> extends <name>{

    <final variables>

    <method headers>
}

The extension of another interface is optional.  A method header is terminated with a semicolon.

In the next example, the interface TrueStack is defined for all implementations that restrict operations to the standard ones on stacks.  Because TrueStack extends Iterable, each implementation must also include an iterator method, and each stack can be traversed with an enhanced for loop.

The code for this interface would be placed in its own source file, named TrueStack.java.  This file can be compiled before any implementing classes are defined.

Example interface:

public interface TrueStack<E> extends Iterable<E>{

    public boolean isEmpty();

    public E peek();

    public E pop();

    public void push(E element);

    public int size();
}

Each implementing class would in turn be placed in its own file.  An interface must be successfully compiled before any of its implementing classes.

Example implementation, based on an ArrayList:

import java.util.*;

public class ArrayStack<E> implements TrueStack<E>{

    private List<E> list;

    public ArrayStack(){
        list = new ArrayList<E>();
    }

    public boolean empty(){
        return list.isEmpty();
    }

    public E peek(){
        return list.get(list.size() – 1);
    }

    public E pop(){
        return list.remove(list.size() – 1);
    }

    public void push(E element){
        list.add(element);
    }

    public int size(){
        return list.size();
    }

    public Iterator<E> iterator(){
        return null;                 # Deferred to another
    }                                # topic
}

© Ken Lambert. All rights reserved.