Sub topic 6
Declaring an Interface
An abstract class can say what its subclasses must do. Java also has a lighter tool for this job, called an interface. An interface is a named list of methods that a class promises to provide. It describes what an object can do. It says nothing about how the object does it.
Why Interfaces Matter
Think of a wall socket. Any lamp, phone charger, or fan can use it, as long as its plug fits the shape. The socket does not care what the device is. An interface works like that plug shape. Any class that fits the shape can be used wherever the interface is expected.
An abstract class sits in a family tree, so it suits closely related classes. An interface can be used by classes that have nothing else in common, such as a Document, a Photo, and a Song that all print.
The Syntax
You declare an interface with the keyword interface instead of class:
interface Printable {
void print();
String summary(int maxLength);
}Here is what each part means:
interface Printablenames the new type. The usual style is to name an interface for what it can do, often with an "-able" ending.void print();is an abstract method, which is a method with no body. It ends with a semicolon, not curly braces.- You do not write
abstractorpublic. In an interface, Java adds both to these methods for you.
What You Cannot Do
An interface is not a full class, so a few things are off limits:
| You try to | Result |
|---|---|
| `new Printable()` | Compile error: you cannot create an object from an interface |
| Add a constructor | Compile error: interfaces have no constructors |
| Add a normal instance field like `int count;` | Compile error: interfaces hold no per-object state |
A Complete Example
An interface does nothing until a class fills in its methods. The program below gives a short preview. The next chapter explains the implements keyword in detail.
interface Printable {
void print();
}
class Document implements Printable {
@Override
public void print() {
System.out.println("Printing document");
}
}
public class Main {
public static void main(String[] args) {
Printable p = new Document();
p.print(); // prints: Printing document
}
}The variable p has the type Printable. You can use an interface as a variable type, even though you cannot create an object from it.
Exercises
Exercise
Write an interface named Playable with two methods: play(), which returns nothing, and getTitle(), which returns a String.
Show answer
interface Playable { void play(); String getTitle(); } Neither method has a body, and you do not need the words public or abstract.
Exercise
A classmate writes Playable p = new Playable();. What happens, and why?
Show answer
It does not compile. An interface is only a list of promised methods, so Java cannot create an object from it. You must create an object of a class that implements Playable.