Loading lessons...
Java Interfaces
Java Interfaces
An interface is a contract of methods that a class promises to implement. Interfaces support multiple inheritance, which classes alone cannot.
Declaring an interface
interface Animal {
public void animalSound();
public void sleep();
}
Methods in an interface are abstract by default.
Implementing an interface
Use the implements keyword:
class Pig implements Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
public void sleep() {
System.out.println("Zzz");
}
}
Multiple interfaces
A class can implement many interfaces at once:
class Demo implements FirstInterface, SecondInterface {
// implement all methods from both interfaces
}
Interface vs abstract class
| Feature | Interface | Abstract class |
|---|---|---|
| Instantiate | No | No |
| Inherit with | implements | extends |
| Multiple inheritance | Yes | No |
TL;DR
- Interfaces declare method contracts.
- Classes implement them with the
implementskeyword. - A class can implement multiple interfaces.