Sub topic 2
Declaring an Interface
What Is an Interface?
An interface is a list of methods that a class promises to provide. It says what an object can do. It does not say how the object does it. You declare an interface with the interface keyword:
interface Drawable {
void draw();
}The draw method has no body. It is an abstract method, which is a method with a name but no code. The class that uses the interface supplies the code.
Implementing an Interface
To implement an interface, a class writes implements and then gives a body to every method in the interface. If it leaves out a method, the program will not compile.
Programming to an Abstract Type
A variable can have an interface as its type. For example, Drawable d can hold any object whose class implements Drawable. Your code then depends only on the promise, draw(), and not on one particular class. This is called programming to an abstract type. It lets you swap in a different class later without changing the code that uses it.
One Class, Many Interfaces
A class can extend only one class. It can implement many interfaces, though. You list them with commas.
interface Drawable {
int MAX_SIZE = 100;
void draw();
}
interface Resizable {
void resize(double factor);
}
class Square implements Drawable, Resizable {
private double side;
Square(double side) {
this.side = side;
}
@Override
public void draw() {
System.out.println("Square of side " + side);
}
@Override
public void resize(double factor) {
side *= factor;
}
}
public class Main {
public static void main(String[] args) {
Square sq = new Square(3.0);
Resizable r = sq;
r.resize(2.0);
Drawable d = sq;
d.draw(); // prints: Square of side 6.0
System.out.println(Drawable.MAX_SIZE); // prints: 100
}
}In this code, the variables r and d both point to the same Square object. Each variable lets you use only the methods of its own interface.
Interface Constants and Implicit Modifiers
A modifier is a keyword such as public or static. Java adds some modifiers to interfaces for you, even when you don't write them:
| You write | Java treats it as |
|---|---|
| `void draw();` | `public abstract void draw();` |
| `int MAX_SIZE = 100;` | `public static final int MAX_SIZE = 100;` |
A field in an interface is therefore a constant, which is a value that never changes. You read it through the interface name, as in Drawable.MAX_SIZE.
Exercise
A class Circle implements Drawable but declares its method as void draw() { } without public. What happens, and why?
Show answer
The code does not compile. Interface methods are public even when you don't write public, and an implementing class cannot give a method weaker access than the interface does. Mark the method public void draw().
Exercise
Can you change Drawable.MAXSIZE with `Drawable.MAXSIZE = 200;`?
Show answer
No. Fields in an interface are public, static, and final, so they are constants and cannot be changed.