- Sometimes it is useful to define a set of functionality without deciding
how that functionality will be implemented. An "abstract" method in an
"abstract" class is an example of this. Examples? maybe "feed" method in
"Animal" would be an abstract method.
- Java lets you define something called an "interface" which is like an
asbtract class that has nothing but abstract methods. When would you want
to do this? Best shown by example - interface in JFC "Comparable" has one
method, namely:
public int compareTo(Object o)
The "Comparable"
interface contains no code, but the definition states what any
implementation should do.
- How to declare an interface? Looks like a class definition but with
word "Interface" instead, e.g.
public Interface Compare { ...
- How to use an interface? Use keyword "implements", e.g.
class Car implements Comparable { ...
- An interface can extend another interface
- If you "implement" an interface, Java compiler will make sure you have
implementations of the functions. Like abstract methods.
- Example for class "Car":
public int compareTo(Object o)
{
// Don't try this if it's not a Car!
if (o instanceof Car) {
Car otherCar = (Car)o;
if (otherCar.tankSize > tankSize) {
return -1;
}
if (otherCar.tankSize == tankSize) {
return 0;
}
return 1;
}
// It wasn't a Car, so we'll just say the two
// objects are equal.
return 0;
}
- What's the value in interface? Why is it better than an abstract class
that has just abstract methods? Because while you can only extend one
class, you can implement as many interfaces as you want.
- Anyone think of other useful interfaces? E.g. "printable", "saveable",
"drawable" - often they are "xxxxable"