Java Reference
In-Depth Information
You already know that an interface is a special type of class. How does an interface differ
from an actual class?
An interface is a type of class that contains only abstract methods and/or named constants.
Interfaces are defined using the reserved word interface in place of the reserved word
class . For example, the definition of the interface WindowListener is:
public interface WindowListener
{
public void windowOpened(WindowEvent e);
public void windowClosing(WindowEvent e);
public void windowClosed(WindowEvent e);
public void windowIconified(WindowEvent e);
public void windowDeiconified(WindowEvent e);
public void windowActivated(WindowEvent e);
public void windowDeactivated(WindowEvent e);
}
The definition of the interface ActionListener is:
public interface ActionListener
{
public void actionPerformed(ActionEvent e);
}
EXAMPLE 10-8
The
following
implements
the
interface s
and
class
ActionListener
WindowListener :
public class ExampleInterfaceImp implements ActionListener,
WindowListener
{
//....
}
Recall that if a class contains an abstract method, it must be declared abstract .
Moreover, you cannot instantiate an object of an abstract class . Therefore, if a
class implements an interface , it must provide definitions for each of the methods
of the interface ; otherwise, you cannot instantiate an object of that class type.
Polymorphism Via Interfaces
As stated above, one of the main uses of interfaces is to allow GUI programs to handle
more than one type of event such as window events, mouse events, and action events.
These events are handled by separate interfaces. An interface can also be used in the
 
 
Search WWH ::




Custom Search