interface
- Java course
- Intermediate
- Lesson 47/116
- 5 min
Learn to define contracts with interface.
What is an interface?
An interface defines the contract of methods that classes will implement. It contains method signatures; no bodies. It starts with the interface keyword.
Example: interface Drawable { void draw(); }. Here Drawable is a contract; draw is declared with its signature only. A class that implements this contract must write the draw method. The interface says what to do; it leaves how to the class. This lets different classes share a common behavior.
Method signatures inside an interface
Methods inside an interface have no body. Only the signature is written: return type, name and parameters. It ends with a semicolon.
Example: interface Speaker { void speak(String msg); }. Here speak has return type void and parameter String msg. No body; only the contract. The implementing class writes the method with its own body. Even if you do not write public, interface methods are implicitly public. This means the contract is always open.
Practice Define the Drawable interface
Define an interface Drawable. Add the void draw() method signature. Then write class Circle implements Drawable; write the public void draw() method with a body that runs System.out.println("Drawing a circle");. In main call new Circle().draw().
Starter code
// Define the Drawable interface
// Write Circle implements Drawable
// Call new Circle().draw() in mainSample solution
interface Drawable {
void draw();
}
class Circle implements Drawable {
public void draw() {
System.out.println("Drawing a circle");
}
}
class Main {
public static void main(String[] args) {
new Circle().draw();
}
}Expected output
Drawing a circle
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which keyword defines an interface?
- interface Correct answer
- class
- contract
- abstract
Explanation: The interface keyword defines a contract.
2 Complete the interface declaration
interface ____ {
void draw();
}
interface Drawable {
void draw();
}
Explanation: Drawable is the interface name.
3 Match the interface parts
| Term | Meaning |
|---|---|
interface |
Contract keyword |
void draw() |
Method signature |
Drawable |
Interface name |
; |
Signature end |