What is an Interface?
Common in everyday life.
– Movie theaters, TVs, VCRs, etc.
Java interface definitions are simple:
– Method headers.
– Field definitions (public static final).
An Interface Definition
interface VCR {
public boolean loadTape(String tapeName);
public boolean eject();
public boolean play();
public boolean pause();
public boolean stop();
public boolean ff();
public boolean rew();
public int getStatus();
public static final int PLAYING = 0, PAUSED = 1,
STOPPED = 2, FORWARD = 3, BACKWARD = 4,
NOTAPE = 5;
}
Implementing an Interface
class PanasonicVCR implements VCR {
...
public boolean eject(){
if(getStatus() != NOTAPE){
setStatus(NOTAPE);
return true;
}
else{
return false;
}
}
...
}
The Iterator interface
public interface Iterator {
public boolean hasNext();
public Object next()
throws NoSuchElementException;
}
LinkedList
public ListIterator listIterator(int index)
Iterator it = l.listIterator(0);
while (it.hasNext()){
Object elm = it.next();
…
}
The Enumeration Interface
public interface Enumeration {
public boolean hasMoreElements();
public Object nextElement()
throws NoSuchElementException;
}
Hashtable
public Enumeration elements()
public Enumeration keys()
Packages
What is a package?
– A package is an encapsulation of classes
possibly stored in multiple files.
Why packages?
– Provide another level of modularity
– Provide another level of protection
Defining and Using Packages
Defining packages
package packageName;
Using packages
import packageName.ClassName;
import packageName.*;
Managing Java source and class files