Interfaces in Java |
Most of the time programmers in Java use class names as types. However there are circumstances where it is very useful to have a type that is not associated with implementations. For example, we wrote a variation of the laundry program that held both Tshirts and Pants. If we had used either Tshirt or Pants as the type of the laundry object, it could not have been associated with both Tshirts and Pants. Instead we define an interface in Java:
import objectdraw.*; import java.awt.*; /** * Interface for a piece of laundry of an arbitrary shape. * @author kim * */ public interface Laundry { /** * Move the laundry relative to its current position * @param xOffset - distance to move horizontally * @param yOffset - distance to move vertically */ void move(double xOffset, double yOffset); /** * Move the laundry to a specific position: * @param x -- coordinates to move laundry to * @param y */ public void moveTo(double x, double y); /** * Determine if pt is in laundry item * @param pt -- location wish to determine if in laundry * @return true if pt is in laundry */ public boolean contains(Location pt); /** * Set the color of the item: * @param newHue -- new color for item */ public void setColor(Color newHue); /** * return color of the item * @return the color of the item. */ public Color getColor(); /** * Remove the item from the canvas */ public void removeFromCanvas(); }
Note that everything listed in an interface MUST be public. As a result, you can drop the use of public.
If we want a class to be used in a context expecting an element of the interface, we must declare that the class implements the interface in the class header:
public class Pants implements Laundry {
The statement that the class implements an interface is a promise that the class has everything promised by the interface. Java uses what is called a nominal type system, meaning that if you don't declare a class implements the interface, then you can't use it as an object of the interface even if it has all the features required. Grace, on the other hand, uses a structural type system, meaning that if an object has all the features required by the type then you can use it as an element of the type.
I like to use interfaces because they allow me to change the definitions of classes without tying me to a particular implementation. As we'll see, they are required in certain frameworks for GUI components.
Interfaces in Java |