Transcript Interfaces
CS2
•
•
•
•
Module 26
Category: OO Concepts
Topic: Interfaces
Objectives
– Interfaces
What is an Interface?
“An interface is a named collection of method definitions (without
definitions). An interface can also declare constants.”
– The Java Tutorial, Sun Microsystems
•
Sounds similar to an abstract class, but has significant
differences:
1. Interfaces cannot have any methods with implementation
2. A class can implement many interfaces, but can inherit from
only one superclass
3. Interfaces are not part of a class hierarchy, so unrelated
classes can implement the same interface.
•
Purpose: Define a protocol of behavior that can be provided
by any class. Any class claiming to “implement” a given
interface is then contractually obligated to provide
implementations of all the methods listed in the interface.
Interface Example
• We want a container class that can sort the items it holds.
• What method will be used to compare two objects?
Will we have such a method?
• We make a kind of specification, a protocol:
– We promise that any object we want to store in this sorting container
class will have a method allowing it to be compared to other objects.
– Also that method will have a known signature.
• How do we formalize this?
• Use of an interface
Interface java.lang.Comparable
Comparable is a predefined interface that is part of Java.
Straight from the API: “This interface imposes a total
ordering on the objects of each class that implements it.”
(Look it up yourself!)
public interface Comparable {
public int compareTo(Object o)
}
Returns:
a negative integer, zero, or a positive integer as the
calling object is less than, equal to, or greater
than the object specified as a parameter.
Suppose...
public class Box implements Comparable {
// Same as before including getVolume method
// but omitted for the sake of the PowerPoint slide
public int compareTo(Object o) {
int retval = -1;
if(o instanceOf Box) {
retVal = getVolume() - ((Box)o).getVolume();
if(retVal == 0)
retVal = 0;
else if(retVal > 0)
retVal = 1;
else
retval = -1;
} // if
return retval;
}
}
If instead we say
interface Constants {
public final static int FEETPERMILE = 5280;
public final static String PROMPT = "Enter a
number";
public final static double PI = 3.141592;
}
• Sample usage:
public class Box implements Constants {
// lots of code omitted
feet = miles * FEETPERMILE;